概述

MCP 提供了一种机制,使 Chainlit 应用能够连接到基于服务器发送事件 (SSE) 的服务或基于命令行的 (stdio) 工具。连接后,您的应用可以发现可用的工具,执行它们,并将它们的响应集成到您的应用流程中。

Chainlit MCP 操作指南

展示使用 Claude 进行 MCP 工具调用的端到端操作指南示例。

连接到 MCP 服务器

联系我们获取企业级 MCP

我们正与公司合作创建其 MCP 堆栈,使 AI 代理能够以标准化方式使用其数据和上下文。填写此 表单

连接类型

Chainlit 支持两种类型的 MCP 连接

  1. SSE (服务器发送事件): 通过 HTTP 连接到远程服务
  2. stdio: 执行本地命令并通过标准 I/O 进行通信

⚠️ 安全警告: stdio 连接类型会在 Chainlit 服务器上生成实际的子进程。仅在受控环境中对可信命令使用此类型。请确保对用户输入进行适当验证,以防止命令注入漏洞。

命令可用性警告: 使用 stdio 连接类型以及 npxuvx 等命令时,这些命令必须在运行 Chainlit 应用的服务器上可用。子进程在服务器上执行,而不是在客户端机器上。

服务器端配置 (config.toml)

您可以通过修改项目的 config.toml 文件(通常位于项目根目录或 .chainlit/config.toml)来全局控制启用哪些 MCP 连接类型并限制允许的 stdio 命令。

[features.mcp] 部分下,您可以分别配置 SSE 和 stdio

[features]
# ... other feature flags

[features.mcp.sse]
    # Enable or disable the SSE connection type globally
    enabled = true

[features.mcp.stdio]
    # Enable or disable the stdio connection type globally
    enabled = true
    # Define an allowlist of executables for the stdio type.
    # Only the base names of executables listed here can be used.
    # This is a crucial security measure for stdio connections.
    # Example: allows running `npx ...` and `uvx ...` but blocks others.
    allowed_executables = [ "npx", "uvx" ]

设置

1. 注册连接处理程序

要在 Chainlit 应用中使用 MCP,您需要实现 on_mcp_connect 处理程序。on_mcp_disconnect 处理程序是可选的,但为了正确清理资源,建议实现。

import chainlit as cl
from mcp import ClientSession

@cl.on_mcp_connect
async def on_mcp_connect(connection, session: ClientSession):
    """Called when an MCP connection is established"""
    # Your connection initialization code here
    # This handler is required for MCP to work
    
@cl.on_mcp_disconnect
async def on_mcp_disconnect(name: str, session: ClientSession):
    """Called when an MCP connection is terminated"""
    # Your cleanup code here
    # This handler is optional

2. 客户端配置

客户端需要通过 Chainlit 界面提供连接详情。这包括

  • 连接名称 (唯一标识符)
  • 客户端类型 (ssestdio)
  • 对于 SSE: URL 端点
  • 对于 stdio: 完整命令 (例如,npx your-tool-packageuvx your-tool-package)

添加 MCP

使用 MCP 连接

检索可用工具

连接后,您可以发现 MCP 服务提供的可用工具

@cl.on_mcp_connect
async def on_mcp(connection, session: ClientSession):
    # List available tools
    result = await session.list_tools()
    
    # Process tool metadata
    tools = [{
        "name": t.name,
        "description": t.description,
        "input_schema": t.inputSchema,
    } for t in result.tools]
    
    # Store tools for later use
    mcp_tools = cl.user_session.get("mcp_tools", {})
    mcp_tools[connection.name] = tools
    cl.user_session.set("mcp_tools", mcp_tools)

执行工具

您可以使用 MCP 会话执行工具

@cl.step(type="tool") 
async def call_tool(tool_use):
    tool_name = tool_use.name
    tool_input = tool_use.input
    
    # Find appropriate MCP connection for this tool
    mcp_name = find_mcp_for_tool(tool_name)
    
    # Get the MCP session
    mcp_session, _ = cl.context.session.mcp_sessions.get(mcp_name)
    
    # Call the tool
    result = await mcp_session.call_tool(tool_name, tool_input)
    
    return result

与 LLM 集成

MCP 工具可以与支持工具调用的 LLM 无缝集成

async def call_model_with_tools():
    # Get tools from all MCP connections
    mcp_tools = cl.user_session.get("mcp_tools", {})
    all_tools = [tool for connection_tools in mcp_tools.values() for tool in connection_tools]
    
    # Call your LLM with the tools
    response = await your_llm_client.call(
        messages=messages,
        tools=all_tools
    )
    
    # Handle tool calls if needed
    if response.has_tool_calls():
        # Process tool calls
        pass
        
    return response

会话管理

MCP 连接在会话级别进行管理。每个 WebSocket 会话可以有多个命名的 MCP 连接。连接会在以下情况清理

  1. 用户显式断开连接
  2. 重用相同的连接名称时 (旧连接被替换)
  3. WebSocket 会话结束时