以编程方式使用文档

LangSmith 工具服务器是一个独立的 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:
    """Greet someone by name."""
    return f"Hello, {name}!"

@tool
def add(x: int, y: int) -> int:
    """Add two numbers."""
    return x + y

TOOLS = [hello, add]

运行服务器:

langchain tools serve

您的工具服务器将在以下地址启动 http://localhost:8000.

通过 MCP 协议调用工具

以下示例列出了可用工具并调用了 add tool:

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 服务器的工具聚合到单一端点中。在您的中配置 MCP 服务器 toolkit.toml:

[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_forecast, math_add).

身份验证

第三方 API 的 OAuth

对于需要访问第三方 API(如 Google、GitHub、Slack 等)的工具,您可以使用 OAuth 身份验证进行 Agent Auth.

在工具中使用 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:
    """Read recent emails from Gmail."""
    credentials = Credentials(token=context.token)
    service = build('gmail', 'v1', credentials=credentials)
    # ... Gmail API calls
    return f"Retrieved {max_results} emails"

带有 auth_provider must: - 拥有 context: Context 作为第一个参数 - 指定至少一个作用域 - 使用 context.token 用于进行身份验证的 API 调用

自定义请求身份验证

自定义身份验证允许您验证请求并与您的身份提供商集成。在您的...中定义一个身份验证处理程序 auth.py file:

from langsmith_tool_server import Auth

auth = Auth()

@auth.authenticate
async def authenticate(authorization: str = None) -> dict:
    """Validate requests and return user identity."""
    if not authorization or not authorization.startswith("Bearer "):
        raise auth.exceptions.HTTPException(
            status_code=401,
            detail="Unauthorized"
        )

    token = authorization.replace("Bearer ", "")
    # Validate token with your identity provider
    user = await verify_token_with_idp(token)

    return {"identity": user.id}

处理程序在每个请求上都会运行,必须返回一个包含以下内容的字典: identity (以及可选的 permissions).