跳到主内容

从 Python 调用 MCP 服务器

本指南展示了一个完整的 Casdoor MCP 服务器 Python 客户端:它获取令牌、建立连接、调用工具并处理缺失 scope 的情况。


学习目标​

  • 通过 client credentials grant 获取带有 MCP scopes 的 access token。
  • 初始化与 MCP 服务器的会话。
  • 调用工具并处理 insufficient_scope 错误。

前置条件​

  • Python 3 及 requests 包
  • Casdoor 中的一个应用,并在 Grant types 中启用了客户端凭证授权
  • 该应用的客户端 ID 和客户端密钥

运行示例​

  1. 保存以下程序,并将服务器 URL 和凭证替换为您自己的值:

    import requests
    import json

    # Server configuration
    server_url = "https://your-casdoor.com/api/mcp"
    token_url = "https://your-casdoor.com/api/login/oauth/access_token"
    client_id = "your-client-id"
    client_secret = "your-client-secret"

    # Get a scoped token for application management
    token_response = requests.post(token_url, data={
    "grant_type": "client_credentials",
    "client_id": client_id,
    "client_secret": client_secret,
    "scope": "read:application write:application"
    })
    access_token = token_response.json()["access_token"]

    # Create a session with the token
    session = requests.Session()
    session.headers.update({
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
    })

    # Initialize the connection
    init_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": {"name": "python-client", "version": "1.0.0"}
    }
    }
    response = session.post(server_url, json=init_request)
    print("Initialize:", response.json())

    # Send initialized notification
    notify_request = {
    "jsonrpc": "2.0",
    "method": "notifications/initialized"
    }
    session.post(server_url, json=notify_request)

    # List available tools (filtered by scopes)
    list_tools_request = {
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list"
    }
    response = session.post(server_url, json=list_tools_request)
    print("Available tools:", response.json())

    # Create a new application (requires write:application scope)
    create_app_request = {
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
    "name": "add_application",
    "arguments": {
    "application": {
    "owner": "my-org",
    "name": "automated-app",
    "displayName": "Automated Application",
    "organization": "my-org"
    }
    }
    }
    }
    response = session.post(server_url, json=create_app_request)
    result = response.json()

    if "error" in result:
    error = result["error"]
    if error.get("code") == -32001 and error.get("message") == "insufficient_scope":
    # Handle insufficient scope error
    error_data = error.get("data", {})
    print(f"Need scope: {error_data.get('required_scope', 'unknown')}")
    print(f"Have scopes: {error_data.get('granted_scopes', [])}")
    else:
    print(f"Error: {error.get('message', 'Unknown error')}")
    else:
    print("Created application:", result)
  2. 运行该程序。

该程序请求具有 application:read 和 application:write 作用域的令牌,因此它可以读取和修改应用。若要将客户端限制为仅读取,请只请求 application:read。此时写入调用将失败并返回 insufficient_scope,程序会报告此错误。

另请参阅​