Logo NimCP

NimCP

Cộng đồng
gokr

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

Nhà phát hànhgokr
Kho mãnimcp
Ngôn ngữNim
Bản fork
6
Sao
24
Công cụ có sẵn
0
Phương thức truyền tảistdio
Danh mục
Giấy phépMIT
Liên kết
  • Kết nối công cụ với quy trình làm việc AI

    NimCP cung cấp các khả năng MCP mà ứng dụng khách và tác nhân AI tương thích có thể sử dụng.

  • 0 công cụ có sẵn

    Xem các thao tác có thể gọi bên dưới, kèm tên và mô tả nếu máy chủ cung cấp.

  • Cấu hình sẵn để sao chép

    Dùng các đoạn cấu hình cài đặt mẫu để thiết lập máy chủ này trong ứng dụng khách MCP bạn muốn dùng.

  • Chỉ số quan tâm đến mã nguồn mở

    24 sao và 6 bản fork từ kho mã được liên kết.

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

Dùng MCP NimCP với nhiều mô hình AI

TypingMind kết nối các công cụ MCP ở cấp không gian làm việc, nên sau khi kết nối NimCP, bạn có thể dùng với nhiều mô hình AI khác nhau trong TypingMind thay vì phải thiết lập riêng cho từng mô hình. MCP này chạy cục bộ thông qua trình kết nối MCP của TypingMind trên thiết bị của bạn.

Hướng dẫn thiết lập để dùng trình kết nối cục bộ

Dùng cách này khi máy chủ MCP cần truy cập các tệp, ứng dụng hoặc tài nguyên riêng tư trên máy tính của bạn.

1

Mở cài đặt MCP

Trong TypingMind, vào Cài đặt, Cài đặt nâng cao, rồi đến Giao thức ngữ cảnh mô hình và chọn Cài trình kết nối.

  1. Mở TypingMind trong trình duyệt của bạn.
  2. Nhấp vào biểu tượng Cài đặt.
  3. Vào Cài đặt nâng cao.
  4. Mở mục Giao thức ngữ cảnh mô hình.
  5. Nhấp vào Cài trình kết nối rồi chọn Thiết bị này.
Màn hình thiết lập trình kết nối MCP của TypingMind với tùy chọn Thiết bị này được chọn
2

Chạy lệnh trình kết nối

Chọn Thiết bị này, sao chép lệnh từ TypingMind và chạy trong Terminal. Giữ tiến trình chạy trong khi bạn dùng MCP.

  1. Sao chép lệnh thiết lập hiển thị trong TypingMind.
  2. Mở Terminal trên macOS hoặc Windows Terminal trên Windows.
  3. Dán và chạy lệnh.
  4. Xác nhận cài đặt gói nếu Terminal hỏi bạn có muốn tiếp tục không.
  5. Giữ tiến trình trong cửa sổ Terminal chạy trong khi dùng các công cụ MCP.
3

Thêm NimCP làm máy chủ

Khi trạng thái trình kết nối là Sẵn sàng, nhấp vào Sửa máy chủ và dán cấu hình máy chủ MCP.

  1. Đợi đến khi trạng thái trình kết nối hiển thị Sẵn sàng.
  2. Nhấp vào Sửa máy chủ.
  3. Dán cấu hình máy chủ MCP của NimCP.
  4. Lưu danh sách máy chủ.
  5. Làm mới nếu bạn muốn xác nhận trình kết nối vẫn sẵn sàng.
Cài đặt MCP của TypingMind hiển thị máy chủ đang hoạt động và nút Sửa máy chủ
{
  "mcpServers": {
    "nimcp": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Dùng kết nối với nhiều mô hình

Lưu danh sách máy chủ, mở Plugin, bật các công cụ MCP của NimCP, sau đó chọn bất kỳ mô hình AI nào được hỗ trợ trong TypingMind và dùng các công cụ trong cuộc trò chuyện hoặc gán chúng cho một tác nhân AI.

  1. Mở trang Plugin trong TypingMind.
  2. Bật các công cụ MCP của NimCP.
  3. Bắt đầu cuộc trò chuyện và chọn mô hình AI bạn muốn dùng.
  4. Dùng các công cụ MCP trong cuộc trò chuyện hoặc gán chúng cho một tác nhân AI.
  5. Chuyển sang mô hình AI khác bất cứ khi nào cần mà không phải kết nối lại MCP.
Cuộc trò chuyện TypingMind dùng các công cụ MCP đã bật với một mô hình AI được chọn
Bạn có thể dùng NimCP giúp tôi làm việc này không?
NimCP
Được. Tôi đã đọc.
Đây là kết quả tôi tìm được bằng NimCP.

Câu hỏi thường gặp

Máy chủ MCP NimCP dùng để làm gì?

NimCP là máy chủ MCP cho phép các ứng dụng AI tương thích kết nối với công cụ và ngữ cảnh bên ngoài. Trong TypingMind, bạn chỉ cần thêm máy chủ MCP này một lần để các công cụ của nó có sẵn trong không gian làm việc AI của bạn.

Bạn có thể dùng MCP NimCP với nhiều mô hình AI trong TypingMind không?

Có. TypingMind kết nối các công cụ MCP ở cấp không gian làm việc, nên bạn có thể dùng NimCP với nhiều mô hình AI như Claude, ChatGPT, Gemini hoặc các mô hình khác đã cấu hình trong TypingMind mà không cần thiết lập máy chủ MCP riêng cho từng mô hình.

Vì sao nên dùng MCP NimCP với TypingMind?

TypingMind là một trong những giao diện trò chuyện với LLM tốt nhất vì tập hợp nhiều mô hình AI, prompt, plugin, tác nhân AI, khóa API và công cụ MCP vào một không gian làm việc. Khi kết nối NimCP, bạn có thể dùng các công cụ MCP của dịch vụ này với những mô hình ưa thích, đồng thời giữ quy trình trò chuyện gọn gàng trong TypingMind.

Làm cách nào để kết nối MCP NimCP với TypingMind?

NimCP hoạt động thông qua trình kết nối MCP cục bộ của TypingMind. Đây là lựa chọn phù hợp nhất khi máy chủ MCP cần truy cập tệp cục bộ, ứng dụng máy tính, công cụ dòng lệnh hoặc tài nguyên riêng trên máy tính của bạn.

MCP NimCP cung cấp những công cụ nào trong TypingMind?

NimCP cung cấp các chức năng MCP mà bạn có thể bật từ trang Plugin của TypingMind để dùng trong trò chuyện hoặc gán cho tác nhân AI.

Bạn có cần chia sẻ khóa API với TypingMind để dùng MCP NimCP không?

Không. TypingMind ưu tiên xử lý cục bộ và cho phép bạn kiểm soát nhà cung cấp mô hình, khóa API, prompt và cấu hình MCP. Nếu NimCP yêu cầu xác thực, hãy thêm các header, cài đặt OAuth hoặc cấu hình cục bộ cần thiết cho máy chủ MCP đó khi tạo kết nối.

Máy chủ MCP liên quan

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇