项目简介: AI-Parrot MCP 服务器是 AI-Parrot 框架的一个核心组件,它将 AI-Parrot 内部定义的工具 (Tools) 按照 Model Context Protocol (MCP) 协议进行封装和暴露。这使得任何遵循 MCP 协议的客户端(如大型语言模型 LLM 客户端)都能通过标准化的 JSON-RPC 请求来发现和调用这些工具,从而扩展其功能。该服务器支持 Stdio 和 HTTP 等多种传输协议。

主要功能点:

  • 标准化工具暴露: 将 AI-Parrot 中的 Python 函数和复杂工具封装为 MCP 工具,并提供标准化的 MCP JSON-RPC 接口供外部调用。
  • 多传输协议支持: 客户端可以通过标准输入输出 (Stdio) 或 HTTP 协议与 MCP 服务器通信。
  • 工具元数据提供: 客户端可以查询服务器以获取所有可用工具的详细定义(包括名称、描述和输入参数的 JSON Schema)。
  • 工具执行: 客户端可以通过 MCP 协议调用特定工具,并接收其执行结果,包括成功响应或错误信息。
  • 可配置性: 允许通过配置项管理允许或阻止暴露的工具,以及配置服务器名称、版本等信息。

安装步骤:

  1. 安装 AI-Parrot 库:
    pip install ai-parrot
  2. (可选)安装其他依赖: 根据你的具体 AI-Parrot 应用需要,可能还需要安装 'uvicorn' (用于 HTTP 服务), 'aiohttp' 等。例如:
    pip install uvicorn aiohttp
  3. 准备 AI-Parrot 工具: 在你的 AI-Parrot 项目中定义和注册 'AbstractTool' 类型的工具。这些工具将被 MCP 服务器自动发现和暴露。

服务器配置: MCP 服务器可以通过两种传输方式启动:Stdio 或 HTTP。下面是 MCP 客户端配置连接到 AI-Parrot MCP 服务器所需的关键信息:

1. Stdio 传输协议配置 (适用于本地进程间通信) 当 AI-Parrot MCP 服务器以 Stdio 模式启动时,MCP 客户端需要配置服务器进程的启动命令及其参数。

{
  "name": "ai-parrot-stdio-server",
  "command": "python",
  "args": ["-m", "parrot.mcp.server", "--transport", "stdio", "--name", "my-tools-server"],
  "description": "连接到本地 AI-Parrot MCP 服务器的 Std-IO 传输通道。",
  "allowed_tools": ["tool_a", "tool_b"],
  "blocked_tools": ["tool_c"]
}
  • 'name': MCP 服务器的自定义名称,例如 "ai-parrot-stdio-server"。
  • 'command': 启动 MCP 服务器进程的命令,例如 "python"。
  • 'args': 传递给 'command' 的参数列表。
    • '-m parrot.mcp.server': 指定运行 'ai-parrot' 库中的 MCP 服务器模块。
    • '--transport stdio': 指定使用标准输入输出 (Stdio) 作为传输协议。
    • '--name my-tools-server': 可选,为 MCP 服务器指定一个名称。
  • 'description': 服务器的描述。
  • 'allowed_tools': (可选)一个字符串列表,指定只允许暴露的工具名称。如果未提供,则暴露所有工具。
  • 'blocked_tools': (可选)一个字符串列表,指定要阻止暴露的工具名称。

2. HTTP 传输协议配置 (适用于网络通信) 当 AI-Parrot MCP 服务器以 HTTP 模式启动时,MCP 客户端需要配置服务器的 URL。

{
  "name": "ai-parrot-http-server",
  "url": "http://localhost:8080/mcp",
  "description": "连接到本地 AI-Parrot MCP 服务器的 HTTP 传输通道。",
  "auth_type": "none",
  "auth_config": {},
  "headers": {"User-Agent": "MCP-Client/1.0"},
  "allowed_tools": ["tool_x", "tool_y"],
  "blocked_tools": ["tool_z"]
}
  • 'name': MCP 服务器的自定义名称,例如 "ai-parrot-http-server"。
  • 'url': MCP 服务器的 HTTP 端点 URL,通常是 'http://<host>:<port>/mcp'。
  • 'description': 服务器的描述。
  • 'auth_type': (可选)认证类型,例如 "none" (无认证), "api_key", "bearer", "oauth", "basic"。
  • 'auth_config': (可选)根据 'auth_type' 提供的认证配置信息。
    • 对于 'api_key':'{"api_key": "YOUR_API_KEY", "header_name": "X-API-Key"}'
    • 对于 'bearer':'{"token": "YOUR_BEARER_TOKEN"}'
    • 对于 'basic':'{"username": "YOUR_USERNAME", "password": "YOUR_PASSWORD"}'
  • 'headers': (可选)一个字典,包含额外的 HTTP 请求头。
  • 'allowed_tools': (可选)一个字符串列表,指定只允许暴露的工具名称。
  • 'blocked_tools': (可选)一个字符串列表,指定要阻止暴露的工具名称。

基本使用方法:

  1. 定义工具: 在 'ai-parrot' 框架中定义你的 'AbstractTool' 子类,例如:
    from ai_parrot.tools import AbstractTool, ToolResult
    from pydantic import BaseModel, Field
    
    class CalculatorArgs(BaseModel):
        a: float = Field(description="First number")
        b: float = Field(description="Second number")
    
    class CalculatorTool(AbstractTool):
        name: str = "calculator"
        description: str = "Adds two numbers together."
        args_schema = CalculatorArgs
    
        async def _execute(self, a: float, b: float) -> ToolResult:
            result = a + b
            return ToolResult(status="success", result=f"The sum is {result}")
  2. 启动 MCP 服务器:
    • Stdio 模式 (在命令行中):
      python -m parrot.mcp.server --transport stdio --name my-math-server
    • HTTP 模式 (在一个 Python 脚本中):
      import asyncio
      from ai_parrot.mcp.server import create_http_mcp_server
      from my_tools_module import CalculatorTool # 导入你定义的工具
      
      async def main():
          server = create_http_mcp_server(
              name="my-math-server",
              host="localhost",
              port=8080,
              tools=[CalculatorTool()] # 注册你的工具
          )
          await server.start()
          print("HTTP MCP Server started at http://localhost:8080/mcp")
          # 保持服务器运行
          while True:
              await asyncio.sleep(3600)
      
      if __name__ == "__main__":
          asyncio.run(main())
  3. MCP 客户端连接: 你的 LLM 客户端或其他 MCP 客户端将使用上述配置信息连接到服务器。例如,在另一个 Python 脚本中,使用 'ai-parrot' 自身的 'MCPClient' 来连接:
    import asyncio
    from ai_parrot.mcp.integration import MCPClient, MCPServerConfig
    
    async def client_example():
        config = MCPServerConfig(
            name="my-math-server-client",
            url="http://localhost:8080/mcp", # 或使用 command 和 args for stdio
            transport="http"
        )
        async with MCPClient(config) as client:
            print("Connected to MCP server.")
            tools = await client.list_tools()
            print("Available tools:")
            for tool_def in tools:
                print(f"- {tool_def.name}: {tool_def.description}")
    
            if any(t.name == "calculator" for t in tools):
                print("\nCalling calculator tool...")
                result = await client.call_tool("calculator", {"a": 10, "b": 25})
                print(f"Calculator result: {result.content[0].text}")
    
    if __name__ == "__main__":
        asyncio.run(client_example())

信息

分类

AI与计算