Logo vun NimCP

NimCP

Communautéit
gokr

A Nim library to easily make MCP servers for use by LLMs

Editeurgokr
Repositorynimcp
SproochNim
Forks
6
Stären
24
Disponibel Tools
0
Transporttypstdio
Kategorien
LizenzMIT
Linken
  • Tools mat KI-Workflows verbannen

    NimCP stellt MCP-Funktioune bereit, déi vu kompatibele KI-Clienten a KI-Agente kënne benotzt ginn.

  • 0 disponibel Tools

    Kuckt Iech déi opruffbar Aktiounen hei drënner un, mat Nimm a Beschreiwungen, wa se vum Server geliwwert ginn.

  • Konfiguratioun fir ze kopéieren

    Benotzt d'Installatiounsbeispiller, fir dëse Server an Ärem bevorzugte MCP-Client ze konfiguréieren.

  • Indicateure fir Open Source

    24 Stären an 6 Forks aus dem verlinkte Repository.

NimCP - Easy Model Context Protocol (MCP) Servers in Nim

Nim License

NimCP is a macro-based library for creating Model Context Protocol (MCP) servers in Nim. It leverages Nim's macro system to provide an incredibly easy-to-use API for building MCP servers that integrate seamlessly with LLM applications.

NOTE: 99.9% of this library was written using Claude Code!

Features

  • Macro-driven API - Define servers, tools, resources, and prompts with simple, declarative syntax
  • Full MCP 2024-11-05 Support - Complete implementation of MCP specification with JSON-RPC 2.0
  • Multiple Transports - Supports stdio, SSE, HTTP, and WebSocket transports
  • Enhanced Type System - Support for objects, unions, enums, optional types, and arrays
  • Automatic Schema Generation - JSON schemas generated from Nim type signatures
  • Request Context System - Progress tracking, cancellation, and request lifecycle management
  • Resource URI Templates - Dynamic URI patterns with parameter extraction (/users/{id})
  • Server Composition - Compose multiple MCP servers into a single interface with prefixes and routing
  • Pluggable Logging - Flexible logging system with multiple handlers, levels, and structured output
  • Middleware Pipeline - Request/response transformation and processing hooks
  • Fluent API - Method chaining patterns for elegant server configuration
  • High Performance - Mummy based HTTP and WebSockets implementation
  • Concurrent Processing - Uses the new taskpools library for stdio transport
  • Minimal Dependencies - Uses only essential, well-maintained packages

Quick Start

Installation

bash
nimble install nimcp

Simple Example

nim
import nimcp
import strformat

let server = mcpServer("my-server", "1.0.0"):
  
  mcpTool:
    proc echo(text: string): string =
      ## Echo back the input text
      return "Echo: " & text
  
  mcpTool:
    proc add(a: float, b: float): string =
      ## Add two numbers together
      return $fmt"Result: {a + b}"

when isMainModule:
  # Use stdio transport (default):
  let transport = newStdioTransport()
  transport.serve(server)
  
  # Or use HTTP transport:
  # let transport = newMummyTransport(8080, "127.0.0.1")
  # transport.serve(server)
  
  # Or use WebSocket transport for real-time communication:
  # let transport = newWebSocketTransport(8080, "127.0.0.1")
  # transport.serve(server)

That's it! Your MCP server is ready to run.

Core Concepts

Tools

Tools are functions that LLM applications can call. Define them with the mcpTool macro that plucks out the tool name, description, and JSON schema from your procedure signature and doc comments:

nim
mcpTool:
  proc calculate(expression: string): string =
    ## Perform mathematical calculations
    ## - expression: Mathematical expression to evaluate
    # Your calculation logic here
    return "Result: 42"

Context-Aware vs Regular Tools

NimCP also supports context aware tools that also receive server context for accessing server state and request information:

nim
# Context aware tools need to have first parameter being an McpRequestContext
mcpTool:
  proc notifyTool(ctx: McpRequestContext, args: JsonNode): McpToolResult =
    ## Log request and track processing
    ctx.info("Processing notification request")
    
    # Your notification logic here
    let message = args.getOrDefault("message", %"").getStr()
    
    ctx.info("Notification processing complete")
    return McpToolResult(content: @[createTextContent("Notification: " & message)])

When to use Context-Aware Tools:

  • Server-initiated events
  • Access to server configuration or transport-specific features
  • Custom logging or middleware integration
  • Request-specific state management

Manual Registration Methods:

  • server.registerTool(tool, handler) - Regular tools
  • server.registerToolWithContext(tool, handler) - Context-aware tools
  • Same pattern applies to resources and prompts

Resources

Resources provide data that can be read by LLM applications:

nim
mcpResource("data://config", "Configuration", "Application configuration"):
  proc get_config(uri: string): string =
    return readFile("config.json")

Prompts

Prompts are reusable templates for LLM interactions:

nim
mcpPrompt("code_review", "Code review prompt", @[
  McpPromptArgument(name: "language", description: some("Programming language")),
  McpPromptArgument(name: "code", description: some("Code to review"))
]):
  proc review_prompt(name: string, args: Table[string, JsonNode]): seq[McpPromptMessage] =
    let language = args.getOrDefault("language", %"unknown").getStr()
    let code = args.getOrDefault("code", %"").getStr()
    
    return @[
      McpPromptMessage(
        role: System,
        content: createTextContent(&"Review this {language} code for best practices and potential issues.")
      ),
      McpPromptMessage(
        role: User,
        content: createTextContent(code)
      )
    ]

Manual Server Creation

For more control, you can create servers manually:

nim
import nimcp

let server = newMcpServer("advanced-server", "2.0.0")

# Register tools manually
let tool = McpTool(
  name: "custom_tool",
  description: some("A custom tool"),
  inputSchema: %*{"type": "object"}
)

proc customHandler(args: JsonNode): McpToolResult =
  return McpToolResult(content: @[createTextContent("Custom result")])

server.registerTool(tool, customHandler)

# Run the server
try:
  let transport = newStdioTransport()
  transport.serve(server)
finally:
  server.shutdown()

Server Composition

NimCP supports composing multiple servers into a single interface - perfect for API gateways:

nim
import nimcp, nimcp/composed_server

# Create individual servers using macro API
let calculatorServer = mcpServer("calculator-service", "1.0.0"):
  mcpTool:
    proc add(a: float, b: float): string =
      ## Add two numbers together
      return fmt"Result: {a + b}"

let fileServer = mcpServer("file-service", "1.0.0"):
  mcpTool:
    proc readFile(path: string): string =
      ## Read contents of a file
      try:
        return readFile(path)
      except IOError as e:
        return fmt"Error reading file: {e.msg}"

# Compose them into a single gateway
let apiGateway = newComposedServer("api-gateway", "1.0.0")

# Mount each service with prefixes for namespacing
apiGateway.mountServerAt("/calc", calculatorServer, some("calc_"))
apiGateway.mountServerAt("/files", fileServer, some("file_"))

# Run the composed server
let transport = newStdioTransport()
transport.serve(apiGateway)

# Tools are now available as: calc_add, file_readFile

Error Handling

NimCP automatically handles JSON-RPC errors, but you can throw exceptions in your handlers:

nim
mcpTool:
  proc validate(data: string): string =
    ## Validate input data
    if data.len == 0:
      raise newException(ValueError, "Empty data parameter")
    return "Valid!"

Examples

Check out the examples/ directory for comprehensive examples and see the examples README for some more info.

Just from command line you can test and list tools with for example:

bash
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | ./examples/calculator_server

If you are using Claude Code, this is how you can add it as an MCP server:

  1. Add the MCP server to Claude Code:
bash
claude mcp add basic_calculator --transport stdio $PWD/examples/basic_calculator
  1. Verify it was added:
bash
claude mcp list
  1. Test the server from within Claude Code:

Once added, you should be able to use the calculator tools directly in Claude Code conversations:

  • add: Add two numbers together
  • multiply: Multiply two numbers
  • power: Calculate exponentiation
  • math://constants: Access mathematical constants resource

Example usage in Claude Code:

  • "Can you add 15 and 27 for me?"
  • "What's 12 raised to the power of 3?"
  • "Show me the mathematical constants"

If the CLI method doesn't work, you can manually edit your MCP configuration file (usually at ~/.claude.json). Just change the path to what you have:

{
  "mcpServers": {
    "calculator_server": {
      "type": "stdio",
      "command": "/path/to/examples/calculator_server",
      "args": [],
      "env": {}
    }
  }
}

Testing

Run the test suite:

bash
nimble test

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License. See LICENSE for details.

MCP Resources

NimCP MCP mat verschiddene KI-Modeller benotzen

TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Soubal NimCP verbonnen ass, kënnt Dir et mat verschiddene KI-Modeller an TypingMind benotzen, amplaz et fir all Modell separat anzeriichten. Dës MCP-Integratioun leeft lokal iwwer den TypingMind-MCP-Connector op Ärem Apparat.

Ariichtungsuleedung fir de lokale Connector ze benotzen

Benotzt dës Optioun, wann den MCP-Server Zougrëff op lokal Fichieren, Appen oder privat Ressourcen op Ärem Computer brauch.

1

D'MCP-Astellungen opmaachen

Gitt an TypingMind op „Astellungen“, „Erweidert Astellungen“, dann op „Model Context Protocol“ a wielt „Connector ariichten“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Klickt op d'Astellungssymbol.
  3. Gitt op „Erweidert Astellungen“.
  4. Maacht d'Sektioun „Model Context Protocol“ op.
  5. Klickt op „Connector ariichten“ a wielt „Dësen Apparat“.
Ariichtungsbildschierm vum TypingMind-MCP-Connector mat „Dësen Apparat“ ausgewielt
2

De Connector-Befeel ausféieren

Wielt „Dësen Apparat“, kopéiert de Befeel aus TypingMind a féiert en am Terminal aus. Loosst de Prozess lafen, wärend Dir MCP benotzt.

  1. Kopéiert den Ariichtungsbefeel, deen TypingMind uweist.
  2. Maacht Terminal op macOS oder Windows Terminal op Windows op.
  3. Pescht de Befeel an a féiert en aus.
  4. Bestätegt d'Installatioun vum Package, wann den Terminal Iech freet, ob Dir weiderfuere wëllt.
  5. Loosst den Terminal an de Prozess doranner lafen, wärend Dir MCP-Tools benotzt.
3

NimCP als Server derbäisetzen

Wann de Connector-Status „Prett“ ass, klickt op „Serveren änneren“ a pescht d'MCP-Serverkonfiguratioun an.

  1. Waart, bis de Connector-Status „Prett“ weist.
  2. Klickt op „Serveren änneren“.
  3. Pescht d'MCP-Serverkonfiguratioun vu NimCP an.
  4. Späichert d'Serverlëscht.
  5. Aktualiséiert, wann Dir kontrolléiere wëllt, ob de Connector nach ëmmer prett ass.
MCP-Astellunge vun TypingMind mat aktivem Server an dem Knäppchen „Serveren änneren“
{
  "mcpServers": {
    "nimcp": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

D'Verbindung mat verschiddene Modeller benotzen

Späichert d'Serverlëscht, maacht „Plugins“ op an aktivéiert d'MCP-Tools vu NimCP. Wielt dann e belibegen ënnerstëtzte KI-Modell an TypingMind a benotzt d'Tools am Chat oder weist se engem KI-Agent zou.

  1. Maacht d'Säit „Plugins“ an TypingMind op.
  2. Aktivéiert d'MCP-Tools vu NimCP.
  3. Start e Chat a wielt de KI-Modell, deen Dir benotze wëllt.
  4. Benotzt d'MCP-Tools am Chat oder weist se engem KI-Agent zou.
  5. Wiesselt bei Bedarf op en anere KI-Modell, ouni MCP nei ze verbannen.
TypingMind-Chat mat aktivéierte MCP-Tools an engem ausgewielte KI-Modell
Hëlleft Dir mir bei dëser Aufgab mat NimCP?
NimCP
Jo. Ech hunn et gelies.
Dat hunn ech mat NimCP fonnt.

Heefeg gestallte Froen

Fir wat gëtt de MCP-Server NimCP benotzt?

NimCP ass e MCP-Server, deen et kompatibele KI-Clienten erlaabt, sech mat externen Tools a Kontext ze verbannen. An TypingMind kënnt Dir dëse MCP-Server eemol derbäisetzen a seng Tools an Ärem KI-Aarbechtsberäich zur Verfügung stellen.

Kann ech NimCP MCP mat méi KI-Modeller an TypingMind benotzen?

Jo. TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Sou kënnt Dir NimCP mat verschiddene KI-Modeller wéi Claude, ChatGPT, Gemini oder anere Modeller benotzen, déi Dir an TypingMind konfiguréiert hutt, ouni de MCP-Server fir all Modell separat anzeriichten.

Firwat NimCP MCP mat TypingMind benotzen?

TypingMind ass eng vun de beschte Benotzeruewerfläche fir LLM-Chat, well et méi KI-Modeller, Prompts, Plugins, KI-Agenten, API-Schlësselen a MCP-Tools an engem Aarbechtsberäich zesummebréngt. Wann NimCP verbonnen ass, kënnt Dir seng MCP-Tools mat Äre bevorzugte Modeller benotzen a gläichzäiteg Är Chataarbecht an TypingMind organiséieren.

Wéi verbannen ech NimCP MCP mat TypingMind?

NimCP leeft iwwer de lokale MCP-Connector vun TypingMind. Dat eegent sech am beschten, wann de MCP-Server Zougrëff op lokal Fichieren, Desktop-Apps, Kommandozeilen-Tools oder privat Ressourcen op Ärem Computer brauch.

Wéi eng Tools stellt NimCP MCP an TypingMind zur Verfügung?

NimCP stellt MCP-Funktiounen zur Verfügung, déi Dir op der Plugins-Säit vun TypingMind aktivéiere kënnt, fir se am Chat ze benotzen oder KI-Agenten zouzeweisen.

Muss ech meng API-Schlëssele mat TypingMind deelen, fir NimCP MCP ze benotzen?

Nee. TypingMind setzt op lokal Veraarbechtung a léisst Iech d'Kontroll iwwer Är Modellubidder, API-Schlësselen, Prompts a MCP-Konfiguratioun. Wann NimCP eng Authentifizéierung verlaangt, setzt déi néideg Headeren, OAuth-Astellungen oder lokal Konfiguratioun fir dee MCP-Server derbäi, wann Dir d'Verbindung erstallt.

Änlech MCP-Serveren

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇