使用说明
MCP Crystal客户端
Crystal的通用、可重用的模型上下文协议(MCP)客户端库,使Crystal应用程序能够连接到MCP服务器并使用其功能。
安装
将此添加到您的应用程序 shard.yml:
dependencies:
mcp-client:
github: ralsina/mcp-client
用法
基础示例
require "mcp-client"
# Create a client with STDIO transport
client = MCP::Client.new("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/directory"])
# Connect to the server
server_info = client.connect
puts "Connected to #{server_info.name} v#{server_info.version}"
# List available tools
tools = client.list_tools
tools.each do |tool|
puts "#{tool.name}: #{tool.description}"
end
# Call a tool
result = client.call_tool("read_file", {"path" => JSON::Any.new("/path/to/file.txt")})
puts result.content.first["text"]?.try(&.as_s)
# Disconnect when done
client.disconnect
使用自定义运输
require "mcp-client"
# Create a custom transport
class MyTransport < MCP::Transport
def connect : Nil
# Your connection logic
end
def disconnect : Nil
# Your disconnect logic
end
def send_message(message : String) : Nil
# Your send logic
end
def receive_message : String?
# Your receive logic
end
def connected? : Bool
# Your connection status
end
end
# Use custom transport
transport = MyTransport.new
client_info = MCP::ClientInfo.new("my-client", "1.0.0")
client = MCP::Client.new(transport, client_info)
检查功能
client = MCP::Client.new("npx", ["-y", "@modelcontextprotocol/server-example"])
client.connect
# Check what the server supports
if client.supports_tools?
puts "Server supports tools"
end
if client.supports_resources?
puts "Server supports resources"
end
# Get full capabilities object
caps = client.server_capabilities
API 参考
MCP::Client
用于与MCP服务器通信的主要客户端类。
构造函数
new(command : String, args : Array(String))-使用STDIO传输创建客户端new(transport : Transport, client_info : ClientInfo)-使用自定义传输创建客户端
方法
connect : ServerInfo-连接并执行初始化握手disconnect : Nil-断开与服务器的连接connected? : Bool-检查当前是否已连接list_tools : Array(Tool)-列出可用工具call_tool(name, arguments) : ToolCallResult-调用带有参数的工具ping : Bool-Ping服务器以检查连接server_capabilities : ServerCapabilities?-获取服务器功能supports_tools? : Bool-检查服务器是否支持工具supports_resources? : Bool-检查服务器是否支持资源supports_prompts? : Bool-检查服务器是否支持提示
类型
MCP::ClientInfo-客户标识(名称、版本)MCP::ServerInfo-服务器信息(名称、版本)MCP::Tool-工具定义(名称、描述、input_schema)MCP::ToolCallResult-调用工具的结果MCP::Error-来自服务器的错误响应MCP::ServerCapabilities-服务器功能
异常
MCP::MCPError-MCP错误的基本异常MCP::MCPConnectionError-连接相关错误MCP::MCPProtocolError-协议相关错误MCP::MCPToolError-工具调用错误
发展
运行测试
crystal spec
建筑物
shards build
运行示例
# Basic example
./bin/basic_tool_client /tmp
# Advanced example
./bin/advanced_usage /tmp
项目状态
目前正在开发中。初始版本支持:
- [x] STDIO传输
- [x] 工具列表和调用
- [x] 基本能力谈判
- [x] 错误处理
计划用于未来版本:
- []HTTP/SSE传输
- []资源支持
- []提示支持
- []日志记录配置
- []进度令牌支持
- []请求取消
贡献
- 叉起来
- 创建功能分支(
git checkout -b my-new-feature) - 提交您的更改(
git commit -am 'Add some feature') - 推到分支(
git push origin my-new-feature) - 创建新的Pull请求
许可证
MIT许可证-有关详细信息,请参阅许可证文件。