主题
LangSmith 工具服务器是一个独立的 MCP 框架,用于构建和部署具有内置身份验证和授权的工具。当您需要以下功能时,请使用工具服务器:
- 创建自定义工具,这些工具与 LangSmith 的 Agent Auth 集成,用于 OAuth 身份验证
- 构建一个 MCP 网关,用于您自己构建的(在 Agent Builder 之外的)智能体
如果您正在使用 Agent Builder,则无需直接与工具服务器交互。Agent Builder 提供了内置工具并支持远程 MCP 服务器,而无需设置工具服务器。
但是,您可以将关联的工具服务器实例配置为 MCP 服务器,这将允许您在您的智能体中使用您的自定义 MCP 服务器。
下载 PyPi 包 以开始使用。
创建自定义工具包
安装 LangSmith 工具服务器和 LangChain CLI:
bash
pip install langsmith-tool-server
pip install langchain-cli-v2创建一个新的工具包:
bash
langchain tools new my-toolkit
cd my-toolkit这将创建一个具有以下结构的工具包:
my-toolkit/
├── pyproject.toml
├── toolkit.toml
└── my_toolkit/
├── __init__.py
├── auth.py
└── tools/
├── __init__.py
└── ...使用 @tool 装饰器定义您的工具:
python
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]运行服务器:
bash
langchain tools serve您的工具服务器将在 http://localhost:8000 上启动。
通过 MCP 协议调用工具
以下是一个列出可用工具并调用 add 工具的示例:
python
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 服务器:
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 等)的工具,您可以使用 Agent Auth 进行 OAuth 身份验证。
在您的工具中使用 OAuth 之前,您需要在 LangSmith 工作区设置中配置一个 OAuth 提供者。有关设置说明,请参阅 Agent Auth 文档。
配置完成后,在您的工具装饰器中指定 auth_provider:
python
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 的工具必须:
- 将
context: Context作为第一个参数 - 指定至少一个作用域
- 使用
context.token进行经过身份验证的 API 调用
自定义请求身份验证
自定义身份验证允许您验证请求并与您的身份提供者集成。在您的 auth.py 文件中定义一个身份验证处理器:
python
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)的字典。