ITADN
JuliaSMLM/ModelContextProtocol.jl
JuliaSMLM/ModelContextProtocol.jl · 文件 下载 ZIP
文件最后提交记录最后更新时间
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

ModelContextProtocol.jl

Stable Dev Build Status Coverage

A Julia 实现的 Model Context Protocol (MCP),通过提供对工具、资源和提示词的标准访问,支持与 Anthropic 的 Claude 等大型语言模型(LLMs)集成。

概述

Model Context Protocol 允许应用程序以标准化的方式向 LLMs 提供上下文和能力。此包在 Julia 中实现了 MCP 2025-11-25 规范(针对旧版客户端协商降级至 2024-11-05),并以 mcp_server() 作为创建和配置服务器的主入口点。

mcp_server() 函数提供了一个灵活的接口,用于:

  • 创建具有自定义名称和配置的 MCP 服务器
  • 手动或自动注册工具、资源和提示词
  • 配置服务器能力和行为
  • 设置基于目录的组件组织

示例:

server = mcp_server(
    name = "my-server",
    version = "1.0.0",            # YOUR server's version (the MCP protocol version is negotiated)
    tools = my_tool,              # Single tool or vector of tools
    resources = my_resource,      # Single resource or vector of resources
    prompts = my_prompt,          # Single prompt or vector of prompts
    description = "Server description",
    auto_register_dir = "path/to/components"  # Optional auto-registration
)

特性

  • Protocol 2025-11-25 支持版本协商,回退至 2024-11-05
  • Transports:stdio(默认)以及支持 SSE 和会话管理的 Streamable HTTP
  • Content types:文本、图像、音频、嵌入资源以及 resource_link 引用
  • Structured tool output:声明一个 output_schema,返回 structuredContent
  • Tool annotations:用于客户端信任决策的行为提示(readOnlyHintdestructiveHint、……)
  • Progress notifications:长时间运行的工具通过上下文感知处理器报告进度
  • Tasks (experimental):后台工具执行,支持状态轮询、阻塞式结果 获取以及取消(每个工具 task_support = :optional
  • OAuth Resource Server(HTTP):Bearer 令牌验证(GitHub 令牌、JWT 声明、RFC 7662 内省)以及 RFC 9728 发现元数据
  • Logging control:客户端通过 logging/setLevel 在运行时调整详细程度; 可选的每请求生命周期日志
  • 从目录布局中自动注册组件

Core Components

该包提供三种主要类型,可注册到 MCP 服务器:

  1. MCPTool:表示 LLM 可调用的函数

    • 具有名称、描述、参数和处理函数
    • LLM 可以调用工具以执行操作或计算
  2. MCPResource:表示 LLM 可读取的数据源

    • 具有 URI、名称、MIME 类型和数据提供函数
    • 为 LLM 提供静态或动态数据访问
  3. MCPPrompt:表示基于模板的提示

    • 具有名称、描述和参数化消息模板
    • 有助于标准化与 LLM 的交互

快速开始

安装

using Pkg
Pkg.add("ModelContextProtocol")

基本示例:手动工具设置

以下是一个创建带有单个工具的 MCP 服务器的最小示例:

using ModelContextProtocol
using JSON3
using Dates

# Create a simple tool that returns the current time
time_tool = MCPTool(
    name = "get_time",
    description = "Get current time in specified format",
    parameters = [
        ToolParameter(
            name = "format",
            type = "string",
            description = "DateTime format string",
            required = true
        )
    ],
    handler = params -> TextContent(
        text = JSON3.write(Dict(
            "time" => Dates.format(now(), params["format"])
        ))
    )
)

# Create and start server with the tool
server = mcp_server(
    name = "time-server",
    description = "Simple MCP server with time tool",
    tools = time_tool
)

# Start the server
start!(server)

当 Claude 连接到该服务器时,它将发现 get_time 工具,并能够使用它向用户提供格式化的时间信息。

使用 input_schema 的高级工具参数

对于需要复杂参数类型(数组、枚举、嵌套对象)的工具,请使用 input_schema 提供完整的 JSON Schema:

using ModelContextProtocol

# Tool with enum and array parameters
search_tool = MCPTool(
    name = "search",
    description = "Search with filters",
    input_schema = Dict{String,Any}(
        "type" => "object",
        "properties" => Dict{String,Any}(
            "query" => Dict{String,Any}(
                "type" => "string",
                "description" => "Search query"
            ),
            "tags" => Dict{String,Any}(
                "type" => "array",
                "items" => Dict{String,Any}("type" => "string"),
                "description" => "Filter tags"
            ),
            "sort" => Dict{String,Any}(
                "type" => "string",
                "enum" => ["relevance", "date", "name"],
                "default" => "relevance"
            )
        ),
        "required" => ["query"]
    ),
    handler = function(params)
        query = params["query"]
        tags = get(params, "tags", String[])
        sort = get(params, "sort", "relevance")
        TextContent(text = "Searching '$query' with $(length(tags)) tags, sorted by $sort")
    end
)

server = mcp_server(
    name = "search-server",
    tools = search_tool
)
start!(server)

当提供 input_schema 时,其优先级高于 parameters 字段,从而允许使用任何有效的 JSON Schema 结构。

基于目录的组织

你也可以在目录结构中组织你的 MCP 组件并自动注册它们:

my_mcp_server/
├── tools/
│   ├── time_tool.jl
│   └── math_tool.jl
├── resources/
│   └── data_source.jl
└── prompts/
    └── templates.jl
using ModelContextProtocol

# Create and start server with all components
server = mcp_server(
    name = "full-server",
    description = "MCP server with auto-registered components",
    auto_register_dir = "my_mcp_server"
)

start!(server)

该包将自动扫描目录结构并注册所有组件:

  • tools/:包含工具定义(MCPTool 实例)
  • resources/:包含资源定义(MCPResource 实例)
  • prompts/:包含提示定义(MCPPrompt 实例)

每个组件文件应导出一个或多个相应类型的实例。它们将被自动发现并注册到服务器。

通过 HTTP 的远程服务器(可选 GitHub-token 认证)

using ModelContextProtocol

server = mcp_server(name = "remote-server", version = "1.0.0", tools = my_tools)

# Token-gate the endpoint (optional): clients send `Authorization: Bearer <GitHub PAT>`
auth = create_github_auth(allowed_users = ["your-github-username"])
meta = create_github_resource_metadata("http://your-host:3000")

server.transport = HttpTransport(host = "0.0.0.0", port = 3000,
                                 auth = auth, resource_metadata = meta)
connect(server.transport)
start!(server)

使用 npx mcp-remote http://your-host:3000 --allow-http 将 Claude Desktop 连接到远程服务器。

来自长时间运行工具的进度

处理程序可以接受第二个上下文参数,并在其工作时流式传输进度:

slow_tool = MCPTool(
    name = "process",
    description = "Process a dataset with progress updates",
    parameters = [],
    handler = (args, ctx) -> begin
        for i in 1:10
            send_progress(ctx, i; total = 10, message = "step $i")  # no-op if client sent no progressToken
            # ... do work ...
        end
        TextContent(text = "done")
    end
)

与 Claude 配合使用

要将你的 MCP 服务器与 Claude 配合使用,你需要:

  1. 配置 Claude Desktop:

    • 前往 File → Settings → Developer
    • 点击 Edit Config 按钮
    • 添加到配置中:
    {
      "mcpServers": {
        "my-server": {
          "command": "julia",
          "args": ["--project=/path/to/project", "server_script.jl"]
        }
      }
    }
  2. 重启 Claude Desktop 应用程序以应用更改

  3. 与 Claude 开始对话,并告知它使用你的服务器:

    Please connect to the MCP server named "my-server" and list its available tools.
    
  4. Claude 将连接到您的服务器,然后可以:

    • 使用服务器的功能列出可用工具
    • 使用适当的参数调用工具
    • 访问资源和提示
    • 向您报告结果

请参阅我们的文档],以获取有关与 Claude 集成的更多详细信息。

许可证

本项目采用 MIT 许可证授权 - 详见 LICENSE 文件。