Skip to main content
LangSmith 工具服务器是一个独立的 MCP 框架,用于构建和部署具有内置身份验证和授权的工具。在以下情况下使用工具服务器:
如果您正在使用 Fleet,则无需直接与工具服务器交互。Fleet 提供 内置工具 并支持 远程 MCP 服务器,无需设置工具服务器。但是,您可以将关联的工具服务器实例配置为 MCP 服务器,这将允许您在代理中使用自定义的 MCP 服务器。
下载 PyPI 包 开始使用。

创建自定义工具包

安装 LangSmith 工具服务器和 LangChain CLI:
pip install langsmith-tool-server
pip install langchain-cli-v2
创建新的工具包:
langchain tools new my-toolkit
cd my-toolkit
这将创建一个具有以下结构的工具包:
my-toolkit/
├── pyproject.toml
├── toolkit.toml
└── my_toolkit/
    ├── __init__.py
    ├── auth.py
    └── tools/
        ├── __init__.py
        └── ...
使用 @tool 装饰器定义您的工具。有关工具模式、返回值、错误处理和 ToolRuntime 的更多信息,请参阅 工具指南
from langsmith_tool_server import tool

@tool
def hello(name: str) -> str:
    """通过姓名问候某人。"""
    return f"Hello, {name}!"

@tool
def add(x: int, y: int) -> int:
    """将两个数字相加。"""
    return x + y

TOOLS = [hello, add]
运行服务器:
langchain tools serve
您的工具服务器将在 http://localhost:8000 上启动。

通过 MCP 协议调用工具

以下是一个列出可用工具并调用 add 工具的示例:
import asyncio
import aiohttp

async def mcp_request(url: str, method: str, params: dict = None):
    async with aiohttp.ClientSession() as session:
        payload = {"jsonrpc": "2.0", "method": method, "params": params or {}, "id": 1}
        async with session.post(f"{url}/mcp", json=payload) as response:
            return await response.json()

async def main():
    url = "http://localhost:8000"

    tools = await mcp_request(url, "tools/list")
    print(f"Tools: {tools}")

    result = await mcp_request(url, "tools/call", {"name": "add", "arguments": {"a": 5, "b": 3}})
    print(f"Result: {result}")

asyncio.run(main())

作为 MCP 网关使用

LangSmith 工具服务器可以充当 MCP 网关,将来自多个 MCP 服务器的工具聚合到单个端点。在您的 toolkit.toml 中配置 MCP 服务器:
[toolkit]
name = "my-toolkit"
tools = "./my_toolkit/__init__.py:TOOLS"

[[mcp_servers]]
name = "weather"
transport = "streamable_http"
url = "http://localhost:8001/mcp/"

[[mcp_servers]]
name = "math"
transport = "stdio"
command = "python"
args = ["-m", "mcp_server_math"]
所有来自已连接 MCP 服务器的工具都通过您服务器的 /mcp 端点公开。MCP 工具会加上其服务器名称前缀以避免冲突(例如 weather_get_forecastmath_add)。

身份验证

第三方 API 的 OAuth

对于需要访问第三方 API(如 Google、GitHub、Slack 等)的工具,您可以使用 Agent Auth 进行 OAuth 身份验证。 在您的工具中使用 OAuth 之前,您需要在 LangSmith 工作区设置中配置 OAuth 提供程序。有关设置说明,请参阅 Agent Auth 文档 配置完成后,在您的工具装饰器中指定 auth_provider
from langsmith_tool_server import tool, Context
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

@tool(
    auth_provider="google",
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
    integration="gmail"
)
async def read_emails(context: Context, max_results: int = 10) -> str:
    """从 Gmail 读取最近的电子邮件。"""
    credentials = Credentials(token=context.token)
    service = build('gmail', 'v1', credentials=credentials)
    # ... Gmail API 调用
    return f"Retrieved {max_results} emails"
具有 auth_provider 的工具必须:
  • context: Context 作为第一个参数
  • 指定至少一个作用域
  • 使用 context.token 进行经过身份验证的 API 调用

自定义请求身份验证

自定义身份验证允许您验证请求并与您的身份提供程序集成。在您的 auth.py 文件中定义身份验证处理程序:
from langsmith_tool_server import Auth

auth = Auth()

@auth.authenticate
async def authenticate(authorization: str = None) -> dict:
    """验证请求并返回用户身份。"""
    if not authorization or not authorization.startswith("Bearer "):
        raise auth.exceptions.HTTPException(
            status_code=401,
            detail="Unauthorized"
        )

    token = authorization.replace("Bearer ", "")
    # 使用您的身份提供程序验证令牌
    user = await verify_token_with_idp(token)

    return {"identity": user.id}
该处理程序在每个请求上运行,并且必须返回一个包含 identity(以及可选的 permissions)的字典。