Claude Code can connect to hundreds of external tools and data sources through the Model Context Protocol (MCP), an open source standard for AI-tool integrations. MCP servers give Claude Code access to your tools, databases, and APIs. Claude Code 可以通过模型上下文协议(MCP)连接到数百个外部工具和数据源,MCP 是一个用于 AI 工具集成的开源标准。 MCP 服务器为 Claude Code 提供对您的工具、数据库和 API 的访问权限。
一,What you can do with MCP MCP能帮你做什么
Implement features from issue trackers: “Add the feature described in JIRA issue ENG-4521 and create a PR on GitHub.” 实现问题跟踪器中的功能:“添加 JIRA 问题 ENG-4521 中描述的功能,并在 GitHub 上创建一个 PR。”
Analyze monitoring data: “Check Sentry and Statsig to check the usage of the feature described in ENG-4521.” 分析监控数据:“检查 Sentry 和 Statsig,以检查 ENG-4521 中描述的功能的使用情况。”
Query databases: “Find emails of 10 random users who used feature ENG-4521, based on our PostgreSQL database.” 查询数据库:“根据我们的 PostgreSQL 数据库,查找 10 个随机使用过 ENG-4521 功能的用户邮箱。”
Integrate designs: “Update our standard email template based on the new Figma designs that were posted in Slack” 集成设计:“根据在 Slack 中发布的新 Figma 设计更新我们的标准电子邮件模板”
Automate workflows: “Create Gmail drafts inviting these 10 users to a feedback session about the new feature.” 自动化工作流:“创建 Gmail 草稿邀请这 10 位用户参加关于新功能的反馈会话。”
是不是很强大。
二,Installing MCP servers 安装 MCP 服务器
MCP servers can be configured in three different ways depending on your needs: MCP 服务器可以根据您的需求以三种不同方式进行配置:
2.1 Option 1: Add a remote HTTP server
选项 1:添加远程 HTTP 服务器
HTTP servers are the recommended option for connecting to remote MCP servers. This is the most widely supported transport for cloud-based services. HTTP 服务器是连接到远程 MCP 服务器的推荐选项。这是云服务最广泛支持的传输方式。
# Basic syntax
claude mcp add --transport http <name> <url>
# Real example: Connect to Notion
claude mcp add --transport http notion https://mcp.notion.com/mcp
# Example with Bearer token
claude mcp add --transport http secure-api https://api.example.com/mcp \
--header "Authorization: Bearer your-token"
2.2 Option 2: Add a remote SSE server
选项 2:添加远程 SSE 服务器
The SSE (Server-Sent Events) transport is deprecated. Use HTTP servers instead, where available. SSE(服务器发送事件)传输已被弃用。在可用的情况下,请使用 HTTP 服务器代替。
# Basic syntax
claude mcp add --transport sse <name> <url>
# Real example: Connect to Asana
claude mcp add --transport sse asana https://mcp.asana.com/sse
# Example with authentication header
claude mcp add --transport sse private-api https://api.company.com/sse \
--header "X-API-Key: your-key-here"
2.3 Option 3: Add a local stdio server
选项 3:添加本地 stdio 服务器
Stdio servers run as local processes on your machine. They’re ideal for tools that need direct system access or custom scripts. Stdio 服务器作为本地进程在你的机器上运行。非常适合需要直接访问系统或自定义脚本的工具。
# Basic syntax
claude mcp add [options] <name> -- <command> [args...]
# Real example: Add Airtable server
claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \
-- npx -y airtable-mcp-server
Important: Option ordering 重要提示:选项顺序
All options (--transport, --env, --scope, --header) must come before the server name. The -- (double dash) then separates the server name from the command and arguments that get passed to the MCP server. 所有选项( --transport , --env , --scope , --header )都必须在服务器名称之前。 -- (双短横线)用于分隔服务器名称和传递给 MCP 服务器的命令和参数。
For example: 例如: claude mcp add --transport stdio myserver -- npx server → runs npx server
claude mcp add --transport stdio --env KEY=value myserver -- python server.py --port 8080 → runs python server.py --port 8080 with KEY=value in environment
This prevents conflicts between Claude’s flags and the server’s flags. 这可以防止 Claude 的标志和服务器标志之间的冲突。
2.4 Managing your servers 管理您的服务器
Once configured, you can manage your MCP servers with these commands: 配置完成后,您可以使用以下命令管理您的 MCP 服务器:
# List all configured servers
claude mcp list
# Get details for a specific server
claude mcp get github
# Remove a server
claude mcp remove github
# (within Claude Code) Check server status
/mcp
2.5 Dynamic tool updates 动态工具更新
Claude Code supports MCP list_changed notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a list_changed notification, Claude Code automatically refreshes the available capabilities from that server.
Claude Code 支持 MCP list_changed 通知,允许 MCP 服务器动态更新其可用的工具、提示和资源,而无需您断开连接并重新连接。 当 MCP 服务器发送 list_changed 通知时,Claude Code 会自动刷新从该服务器获取的可用的功能。
Tips: 提示:
Use the --scope flag to specify where the configuration is stored: 使用 --scope 标志指定配置存储的位置:
1,local (default): Available only to you in the current project (was called project in older versions) local (默认): 仅在当前项目中可用(旧版本称为 project )
2,project: Shared with everyone in the project via .mcp.json file project : 通过 .mcp.json 文件与项目中的所有人共享
3,user: Available to you across all projects (was called global in older versions) user : 在所有项目中都可用(旧版本称为 global )
Set environment variables with --env flags (for example, --env KEY=value) 使用 --env 标志设置环境变量(例如, --env KEY=value )
Configure MCP server startup timeout using the MCP_TIMEOUT environment variable (for example, MCP_TIMEOUT=10000 claude sets a 10-second timeout) 使用 MCP_TIMEOUT 环境变量配置 MCP 服务器启动超时(例如, MCP_TIMEOUT=10000 claude 设置 10 秒超时)
Claude Code will display a warning when MCP tool output exceeds 10,000 tokens. To increase this limit, set the MAX_MCP_OUTPUT_TOKENS environment variable (for example, MAX_MCP_OUTPUT_TOKENS=50000) 当 MCP 工具输出超过 10,000 个 token 时,Claude Code 会显示警告。要增加此限制,设置 MAX_MCP_OUTPUT_TOKENS 环境变量(例如, MAX_MCP_OUTPUT_TOKENS=50000 )
Use /mcp to authenticate with remote servers that require OAuth 2.0 authentication 使用 /mcp 与需要 OAuth 2.0 认证的远程服务器进行身份验证
Windows Users: On native Windows (not WSL), local MCP servers that use npx require the cmd /c wrapper to ensure proper execution. Windows 用户:在原生 Windows(非 WSL)上,使用 npx 的本地 MCP 服务器需要 'cmd /c' 包装器以确保正常运行。
# This creates command="cmd" which Windows can execute
claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package
Without the cmd /c wrapper, you’ll encounter “Connection closed” errors because Windows cannot directly execute npx. 没有 cmd /c 包装,你将遇到“连接已关闭”的错误,因为 Windows 不能直接执行 npx 。
三,MCP installation scopes MCP 安装范围
MCP servers can be configured at three different scope levels, each serving distinct purposes for managing server accessibility and sharing. Understanding these scopes helps you determine the best way to configure servers for your specific needs. MCP 服务器可以在三个不同的作用域级别进行配置,每个级别都用于管理服务器可访问性和共享,具有不同的用途。了解这些作用域有助于您根据具体需求确定配置服务器的最佳方式。
3.1 Local scope 本地作用域
Local-scoped servers represent the default configuration level and are stored in ~/.claude.json under your project’s path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn’t be shared. 本地作用域的服务器代表默认的配置级别,存储在您项目路径下的 ~/.claude.json 中。这些服务器仅对您私有,并且仅在当前项目目录内工作时才可访问。 这种作用域非常适合个人开发服务器、实验性配置或包含不应共享的敏感凭证的服务器。
The term “local scope” for MCP servers differs from general local settings. MCP local-scoped servers are stored in ~/.claude.json (your home directory), while general local settings use .claude/settings.local.json (in the project directory). MCP 服务器的“本地作用域”术语与一般本地设置不同。MCP 本地作用域的服务器存储在 ~/.claude.json (您的家目录)中,而一般本地设置使用 .claude/settings.local.json (在项目目录中)。
# Add a local-scoped server (default)
claude mcp add --transport http stripe https://mcp.stripe.com
# Explicitly specify local scope
claude mcp add --transport http stripe --scope local https://mcp.stripe.com
3.2 Project scope 项目范围
Project-scoped servers enable team collaboration by storing configurations in a .mcp.json file at your project’s root directory. This file is designed to be checked into version control, ensuring all team members have access to the same MCP tools and services. When you add a project-scoped server, Claude Code automatically creates or updates this file with the appropriate configuration structure. 项目范围的服务器在您项目的根目录 .mcp.json 文件中,实现团队协作。此文件设计为提交到版本控制,确保所有团队成员都能访问相同的 MCP 工具和服务。当您添加项目范围的服务器时,Claude Code 会自动创建或更新此文件,并包含适当的配置结构。
# Add a project-scoped server
claude mcp add --transport http paypal --scope project https://mcp.paypal.com/mcp
The resulting .mcp.json file follows a standardized format: 生成的 .mcp.json 文件遵循标准格式:
{
"mcpServers": {
"shared-server": {
"command": "/path/to/server",
"args": [],
"env": {}
}
}
}
For security reasons, Claude Code prompts for approval before using project-scoped servers from .mcp.json files. If you need to reset these approval choices, use the claude mcp reset-project-choices command. 出于安全原因,Claude Code 在使用来自 .mcp.json 文件的项目范围服务器前会提示您进行审批。如果您需要重置这些审批选择,请使用 claude mcp reset-project-choices 命令。
3.3 User scope 用户范围
User-scoped servers are stored in ~/.claude.json and provide cross-project accessibility, making them available across all projects on your machine while remaining private to your user account. This scope works well for personal utility servers, development tools, or services you frequently use across different projects. 用户范围的服务器存储在 ~/.claude.json 中,提供跨项目访问能力,在您机器上的所有项目中可用,同时保持对您用户账户的私密性。这种范围非常适合个人实用服务器、开发工具或在不同项目中频繁使用的服务。
# Add a user server
claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic
3.4 Choosing the right scope 选择正确的范围
Select your scope based on: 根据以下情况选择您的范围:
Local scope: Personal servers, experimental configurations, or sensitive credentials specific to one project 本地作用域:个人服务器、实验性配置或特定于一个项目的敏感凭证
Project scope: Team-shared servers, project-specific tools, or services required for collaboration 项目作用域:团队共享服务器、项目特定工具或协作所需的服务
User scope: Personal utilities needed across multiple projects, development tools, or frequently used services 用户作用域:跨多个项目所需的个人工具、开发工具或常用服务
Where are MCP servers stored? MCP 服务器存储在哪里?
User and local scope: ~/.claude.json (in the mcpServers field or under project paths) 用户和本地作用域: ~/.claude.json (在 mcpServers 字段中或项目路径下)
Project scope: .mcp.json in your project root (checked into source control) 项目作用域: .mcp.json 在您的项目根目录(已提交到源代码控制)
Managed: managed-mcp.json in system directories 受管理: managed-mcp.json 在系统目录中
3.5 Scope hierarchy and precedence
作用域层次结构和优先级
MCP server configurations follow a clear precedence hierarchy. When servers with the same name exist at multiple scopes, the system resolves conflicts by prioritizing local-scoped servers first, followed by project-scoped servers, and finally user-scoped servers. This design ensures that personal configurations can override shared ones when needed. MCP 服务器配置遵循清晰的优先级层次。当在多个范围内存在同名的服务器时,系统优先考虑本地范围的服务器,其次是项目范围的服务器,最后是用户范围的服务器来解决冲突。这种设计确保在需要时个人配置可以覆盖共享配置。
3.6 Environment variable expansion in .mcp.json
.mcp.json 中的环境变量扩展
Claude Code supports environment variable expansion in .mcp.json files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys. Claude Code 支持在 .mcp.json 文件中进行环境变量扩展,允许团队共享配置,同时保持针对特定机器的路径和敏感值(如 API 密钥)的灵活性。
Supported syntax: 支持的语法:
{VAR} - 展开为环境变量 VAR 的值
{VAR:-default} - 如果设置了 VAR ,则展开为 VAR ,否则使用 default
Expansion locations: Environment variables can be expanded in: 展开位置:环境变量可以在以下位置展开:
command - The server executable path command - 服务器可执行路径
args - Command-line arguments args - 命令行参数
env - Environment variables passed to the server env - 传递给服务器的环境变量
url - For HTTP server types url - 适用于 HTTP 服务器类型
headers - For HTTP server authentication headers - 适用于 HTTP 服务器认证
Example with variable expansion: 使用变量扩展的示例:
{
"mcpServers": {
"api-server": {
"type": "http",
"url": "${API_BASE_URL:-https://api.example.com}/mcp",
"headers": {
"Authorization": "Bearer ${API_KEY}"
}
}
}
}
If a required environment variable is not set and has no default value, Claude Code will fail to parse the config. 如果必需的环境变量未设置且没有默认值,Claude Code 将无法解析配置。
四,Practical examples 实用示例
Example: Monitor errors with Sentry
示例:使用 Sentry 监控错误
# 1. Add the Sentry MCP server
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
# 2. Use /mcp to authenticate with your Sentry account
> /mcp
# 3. Debug production issues
> "What are the most common errors in the last 24 hours?" 过去24小时内最常见的错误是什么
> "Show me the stack trace for error ID abc123" 请显示错误ID abc123的堆栈跟踪
> "Which deployment introduced these new errors?"是哪个部署引入了这些新错误
Example: Connect to GitHub for code reviews
示例:连接到 GitHub 进行代码审查
# 1. Add the GitHub MCP server
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
# 2. In Claude Code, authenticate if needed
> /mcp
# Select "Authenticate" for GitHub
# 3. Now you can ask Claude to work with GitHub
> "Review PR #456 and suggest improvements"
> "Create a new issue for the bug we just found"
> "Show me all open PRs assigned to me"
Example: Query your PostgreSQL database
示例:查询 PostgreSQL 数据库
# 1. Add the database server with your connection string
claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \
--dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"
# 2. Query your database naturally
> "What's our total revenue this month?" 我们这个月的总收入是多少
> "Show me the schema for the orders table"
> "Find customers who haven't made a purchase in 90 days"
五,Authenticate with remote MCP servers
使用远程 MCP 服务器进行认证
Many cloud-based MCP servers require authentication. Claude Code supports OAuth 2.0 for secure connections. 许多基于云的 MCP 服务器需要认证。Claude Code 支持 OAuth 2.0 以建立安全连接。
1,Add the server that requires authentication 添加需要认证的服务器
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
2,Use the /mcp command within Claude Code 在 Claude Code 中使用/mcp 命令
In Claude code, use the command: 在 Claude 代码中使用命令:
> /mcp
Then follow the steps in your browser to login. 然后在浏览器中按照步骤登录。
Tips: 提示:
Authentication tokens are stored securely and refreshed automatically 认证令牌会安全存储并自动刷新
Use “Clear authentication” in the /mcp menu to revoke access 在 /mcp 菜单中使用“清除认证”来撤销访问
If your browser doesn’t open automatically, copy the provided URL 如果浏览器没有自动打开,请复制提供的 URL
OAuth authentication works with HTTP servers OAuth 认证适用于 HTTP 服务器
Use pre-configured OAuth credentials
使用预配置的 OAuth 凭证
Some MCP servers don’t support automatic OAuth setup. If you see an error like “Incompatible auth server: does not support dynamic client registration,” the server requires pre-configured credentials. Register an OAuth app through the server’s developer portal first, then provide the credentials when adding the server. 一些 MCP 服务器不支持自动 OAuth 设置。如果你看到类似“不兼容的认证服务器:不支持动态客户端注册”的错误,则该服务器需要预配置的凭证。首先通过服务器的开发者门户注册一个 OAuth 应用,然后在添加服务器时提供凭证。具体操作如下:
1,Register an OAuth app with the server 向服务器注册 OAuth 应用
Create an app through the server’s developer portal and note your client ID and client secret. 通过服务器的开发者门户创建一个应用程序,并记下您的客户端 ID 和客户端密钥。
Many servers also require a redirect URI. If so, choose a port and register a redirect URI in the format http://localhost:PORT/callback. Use that same port with --callback-port in the next step. 许多服务器还要求一个重定向 URI。如果是这样,选择一个端口,并以 http://localhost:PORT/callback 的格式注册重定向 URI。在下一步中,给 --callback-port 使用相同的端口。
2,Add the server with your credentials 添加带有您凭证的服务器
The port used for --callback-port can be any available port. It just needs to match the redirect URI you registered in the previous step. 用于 --callback-port 的端口可以是任何可用的端口。它只需要与您在上一步中注册的重定向 URI 相匹配。
Use --client-id to pass your app’s client ID. The --client-secret flag prompts for the secret with masked input: 使用 --client-id 传递您的应用的客户端 ID。 --client-secret 标志会提示您使用掩码来输入密钥:
claude mcp add --transport http \
--client-id your-client-id --client-secret --callback-port 8080 \
my-server https://mcp.example.com/mcp
3,Authenticate in Claude Code 在 Claude Code 中进行身份验证
Run /mcp in Claude Code and follow the browser login flow. 在 Claude Code 中运行 /mcp 并遵循浏览器登录流程。
Run /mcp in Claude Code and follow the browser login flow.
Tips: 提示:
The client secret is stored securely in your system keychain (macOS) or a credentials file, not in your config 客户端密钥安全地存储在您的系统密钥串(macOS)或凭证文件中,而不是在您的配置中。
If the server uses a public OAuth client with no secret, use only --client-id without --client-secret 如果服务器使用没有密钥的公开 OAuth 客户端,请仅使用 --client-id 而不使用 --client-secret
These flags only apply to HTTP and SSE transports. They have no effect on stdio servers 这些标志仅适用于 HTTP 和 SSE 传输。它们对 stdio 服务器无效
Use claude mcp get to verify that OAuth credentials are configured for a server 使用 claude mcp get 验证服务器是否配置了 OAuth 凭证
六,Add MCP servers from JSON configuration
从 JSON 配置中添加 MCP 服务器
If you have a JSON configuration for an MCP server, you can add it directly: 如果你有一个 MCP 服务器的 JSON 配置,可以直接添加:
1,Add an MCP server from JSON 从 JSON 添加 MCP 服务器
# Basic syntax
claude mcp add-json <name> '<json>'
# Example: Adding an HTTP server with JSON configuration
claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}'
# Example: Adding a stdio server with JSON configuration
claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'
# Example: Adding an HTTP server with pre-configured OAuth credentials
claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret
2,Verify the server was added 验证服务器是否已添加
claude mcp get weather-api
Tips: 提示:
Make sure the JSON is properly escaped in your shell 确保 JSON 在您的 shell 中正确转义
The JSON must conform to the MCP server configuration schema JSON 必须符合 MCP 服务器配置模式
You can use --scope user to add the server to your user configuration instead of the project-specific one 您可以使用 --scope user 将服务器添加到您的用户配置中,而不是项目特定的配置
七,Import MCP servers from Claude Desktop
从 Claude Desktop 导入 MCP 服务器
If you’ve already configured MCP servers in Claude Desktop, you can import them: 如果您已经在 Claude Desktop 中配置了 MCP 服务器,也可以导入它们:
1,Import servers from Claude Desktop 从 Claude Desktop 导入服务器
# Basic syntax
claude mcp add-from-claude-desktop
2,Select which servers to import 选择要导入的服务器
After running the command, you’ll see an interactive dialog that allows you to select which servers you want to import. 运行命令后,您将看到一个交互式对话框,允许您选择要导入的服务器。
3,Verify the servers were imported 验证服务器是否已导入
claude mcp list
Tips: 提示:
This feature only works on macOS and Windows Subsystem for Linux (WSL) 此功能仅在 macOS 和 Windows 子系统 for Linux (WSL) 上工作
It reads the Claude Desktop configuration file from its standard location on those platforms 它在对应平台的标准位置读取 Claude 桌面配置文件
Use the --scope user flag to add servers to your user configuration 使用 --scope user 标志将服务器添加到您的用户配置
Imported servers will have the same names as in Claude Desktop 导入的服务器将具有与 Claude 桌面相同的名称
If servers with the same names already exist, they will get a numerical suffix (for example, server_1) 如果已存在同名服务器,它们将获得数字后缀(例如, server_1 )
八,MCP output limits and warnings
MCP 输出限制和警告
When MCP tools produce large outputs, Claude Code helps manage the token usage to prevent overwhelming your conversation context: 当 MCP 工具产生大量输出时,Claude Code 通过以下3种方式帮助管理token使用,以防止您的对话上下文被淹没:
1,Output warning threshold: Claude Code displays a warning when any MCP tool output exceeds 10,000 tokens 输出警告阈值:当任何 MCP 工具输出超过 10,000 个 token 时,Claude Code 会显示警告
2,Configurable limit: You can adjust the maximum allowed MCP output tokens using the MAX_MCP_OUTPUT_TOKENS environment variable 可配置限制:您可以使用 MAX_MCP_OUTPUT_TOKENS 环境变量调整允许的最大 MCP 输出 token 数
3,Default limit: The default maximum is 25,000 tokens 默认限制:默认最大值为 25,000 个 token
To increase the limit for tools that produce large outputs: 为产生大量输出的工具增加限制:
# Set a higher limit for MCP tool outputs
export MAX_MCP_OUTPUT_TOKENS=50000
claude
This is particularly useful when working with MCP servers that: 这在处理以下功能的 MCP 服务器时特别有用:
Query large datasets or databases 查询大型数据集或数据库
Generate detailed reports or documentation 生成详细报告或文档
Process extensive log files or debugging information 处理大量日志文件或调试信息
If you frequently encounter output warnings with specific MCP servers, consider increasing the limit or configuring the server to paginate or filter its responses. 如果你经常遇到与特定 MCP 服务器的输出警告,请考虑增加限制或配置服务器以分页或过滤其响应。
九,Scale with MCP Tool Search
使用 MCP 工具搜索扩展
When you have many MCP servers configured, tool definitions can consume a significant portion of your context window. MCP Tool Search solves this by dynamically loading tools on-demand instead of preloading all of them. 当您配置了多个 MCP 服务器时,工具定义可能会占用您上下文窗口的很大一部分。MCP 工具搜索通过按需动态加载工具而不是预加载所有工具来解决这个问题。
How it works 工作原理
Claude Code automatically enables Tool Search when your MCP tool descriptions would consume more than 10% of the context window. You can adjust this threshold or disable tool search entirely. When triggered: Claude Code 在您的 MCP 工具描述占用超过 10% 的上下文窗口时自动启用工具搜索。您可以调整此阈值或完全禁用工具搜索。当触发时:
1,MCP tools are deferred rather than loaded into context upfront MCP 工具会被延迟加载而不是在上下文中预先加载
2,Claude uses a search tool to discover relevant MCP tools when needed Claude 在需要时使用搜索工具来发现相关的 MCP 工具
3,Only the tools Claude actually needs are loaded into context 只有 Claude 实际需要的工具会被加载到上下文中
4,MCP tools continue to work exactly as before from your perspective MCP 工具从您的角度来看,仍然按预期工作
For MCP server authors 对于 MCP 服务器作者
If you’re building an MCP server, the server instructions field becomes more useful with Tool Search enabled. Server instructions help Claude understand when to search for your tools, similar to how skills work. 如果您正在构建 MCP 服务器,启用工具搜索后,服务器指令字段将更有用。服务器指令有助于 Claude 理解何时搜索您的工具,类似于Skills的工作方式。
Add clear, descriptive server instructions that explain: 添加清晰、描述性的服务器说明,解释:
1,What category of tasks your tools handle 你的工具处理哪些类别的任务
2,When Claude should search for your tools Claude 何时应该搜索你的工具
3,Key capabilities your server provides 你的服务器提供的关键功能
Configure tool search 配置工具搜索
Tool search runs in auto mode by default, meaning it activates only when your MCP tool definitions exceed the context threshold. If you have few tools, they load normally without tool search. This feature requires models that support tool_reference blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search. 工具搜索默认以自动模式运行,这意味着它仅在您的 MCP 工具定义超过上下文阈值时才会激活。如果您工具较少,它们会正常加载而无需工具搜索。 此功能需要支持 tool_reference 块的模型:Sonnet 4 及更高版本,或 Opus 4 及更高版本。Haiku 模型不支持工具搜索。
Control tool search behavior with the ENABLE_TOOL_SEARCH environment variable: 通过 ENABLE_TOOL_SEARCH 环境变量控制工具搜索行为,有下面4种值
1,auto
Activates when MCP tools exceed 10% of context (default) 在 MCP 工具超过 10%的上下文时激活(默认)
2, auto:
Activates at custom threshold, where is a percentage (e.g., auto:5 for 5%) 在自定义阈值时激活,其中 是一个百分比(例如, auto:5 表示 5%)
3, true
Always enabled 始终启用
4, false
Disabled, all MCP tools loaded upfront 禁用,所有 MCP 工具一开始就加载
# Use a custom 5% threshold
ENABLE_TOOL_SEARCH=auto:5 claude
# Disable tool search entirely
ENABLE_TOOL_SEARCH=false claude
Or set the value in your settings.json env field. 或者在你的 settings.json 中的 env 字段设置值。
You can also disable the MCPSearch tool specifically using the disallowedTools setting: 你也可以使用 disallowedTools 设置来特别禁用 MCPSearch 工具:
{
"permissions": {
"deny": ["MCPSearch"]
}
}
看来它本身也是一个工具
十,Managed MCP configuration
受管理的 MCP 配置
For organizations that need centralized control over MCP servers, Claude Code supports two configuration options: 对于需要集中控制 MCP 服务器的组织,Claude Code 支持两种配置选项:
Exclusive control with managed-mcp.json: Deploy a fixed set of MCP servers that users cannot modify or extend 使用 managed-mcp.json 实现独占控制:部署一组固定的 MCP 服务器,用户无法修改或扩展
Policy-based control with allowlists/denylists: Allow users to add their own servers, but restrict which ones are permitted 基于策略的控制,使用允许列表/拒绝列表:允许用户添加自己的服务器,但限制哪些服务器被允许
These options allow IT administrators to: 这些选项允许 IT 管理员:
Control which MCP servers employees can access: Deploy a standardized set of approved MCP servers across the organization 控制员工可以访问哪些 MCP 服务器:在组织内部署一套标准的被批准的 MCP 服务器
Prevent unauthorized MCP servers: Restrict users from adding unapproved MCP servers 阻止未经授权的 MCP 服务器:限制用户添加未经批准的 MCP 服务器
Disable MCP entirely: Remove MCP functionality completely if needed 完全禁用 MCP:如果需要,完全移除 MCP 功能
Option 1: Exclusive control with managed-mcp.json
选项 1:通过 managed-mcp.json 实现独占控制
When you deploy a managed-mcp.json file, it takes exclusive control over all MCP servers. Users cannot add, modify, or use any MCP servers other than those defined in this file. This is the simplest approach for organizations that want complete control. 当你部署一个 managed-mcp.json 文件时,它将独占控制所有 MCP 服务器。用户无法添加、修改或使用此文件中未定义的任何 MCP 服务器。这是希望完全控制的组织最简单的方法。
System administrators deploy the configuration file to a system-wide directory: 系统管理员将配置文件部署到系统级目录:
macOS: /Library/Application Support/ClaudeCode/managed-mcp.json Linux and WSL: /etc/claude-code/managed-mcp.json Windows: C:\Program Files\ClaudeCode\managed-mcp.json
These are system-wide paths (not user home directories like ~/Library/...) that require administrator privileges. They are designed to be deployed by IT administrators. 这些是全局系统路径(而非用户主目录如 ~/Library/... ),需要管理员权限。它们是为 IT 管理员设计的部署路径。
The managed-mcp.json file uses the same format as a standard .mcp.json file: managed-mcp.json 文件与标准 .mcp.json 文件使用相同格式:
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/"
},
"sentry": {
"type": "http",
"url": "https://mcp.sentry.dev/mcp"
},
"company-internal": {
"type": "stdio",
"command": "/usr/local/bin/company-mcp-server",
"args": ["--config", "/etc/company/mcp-config.json"],
"env": {
"COMPANY_API_URL": "https://internal.company.com"
}
}
}
}
Option 2: Policy-based control with allowlists and denylists
选项 2:基于策略的控制,使用允许列表和拒绝列表
Instead of taking exclusive control, administrators can allow users to configure their own MCP servers while enforcing restrictions on which servers are permitted. This approach uses allowedMcpServers and deniedMcpServers in the managed settings file. 管理员不必独占控制权,可以允许用户自行配置自己的 MCP 服务器,同时强制执行对允许服务器的限制。这种方法在管理设置文件中使用 allowedMcpServers 和 deniedMcpServers 。
Choosing between options: Use Option 1 (managed-mcp.json) when you want to deploy a fixed set of servers with no user customization. Use Option 2 (allowlists/denylists) when you want to allow users to add their own servers within policy constraints. 在选项之间进行选择:当你想要部署一组固定的服务器且无需用户自定义时,请使用选项 1( managed-mcp.json )。当你想要允许用户在策略约束内添加自己的服务器时,请使用选项 2(允许列表/拒绝列表)。
Restriction options 限制选项
Each entry in the allowlist or denylist can restrict servers in three ways: 允许列表或拒绝列表中的每个条目都可以通过三种方式限制服务器:
1,By server name (serverName): Matches the configured name of the server 通过服务器名称( serverName ):匹配服务器的配置名称
2,By command (serverCommand): Matches the exact command and arguments used to start stdio servers 通过命令( serverCommand ):匹配启动 stdio 服务器的确切命令和参数
3,By URL pattern (serverUrl): Matches remote server URLs with wildcard support 通过 URL 模式( serverUrl ):匹配带通配符的服务器远程 URL
Important: Each entry must have exactly one of serverName, serverCommand, or serverUrl. 重要提示:每个条目必须正好有一个 serverName 、 serverCommand 或 serverUrl 。
Example configuration 示例配置
{
"allowedMcpServers": [
// Allow by server name
{ "serverName": "github" },
{ "serverName": "sentry" },
// Allow by exact command (for stdio servers)
{ "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },
{ "serverCommand": ["python", "/usr/local/bin/approved-server.py"] },
// Allow by URL pattern (for remote servers)
{ "serverUrl": "https://mcp.company.com/*" },
{ "serverUrl": "https://*.internal.corp/*" }
],
"deniedMcpServers": [
// Block by server name
{ "serverName": "dangerous-server" },
// Block by exact command (for stdio servers)
{ "serverCommand": ["npx", "-y", "unapproved-package"] },
// Block by URL pattern (for remote servers)
{ "serverUrl": "https://*.untrusted.com/*" }
]
}
How command-based restrictions work
命令限制如何工作
1,Exact matching: 精确匹配: Command arrays must match exactly - both the command and all arguments in the correct order 命令数组必须完全匹配——包括命令本身以及所有参数,且顺序必须正确
Example: ["npx", "-y", "server"] will NOT match ["npx", "server"] or ["npx", "-y", "server", "--flag"] 示例: ["npx", "-y", "server"] 将不会匹配 ["npx", "server"] 或 ["npx", "-y", "server", "--flag"]
2,Stdio server behavior: stdio 服务器行为:
When the allowlist contains any serverCommand entries, stdio servers must match one of those commands 当允许列表包含任何 serverCommand 条目时,stdio 服务器必须匹配其中一条命令
Stdio servers cannot pass by name alone when command restrictions are present 当存在命令限制时,stdio 服务器不能仅通过名称通过
This ensures administrators can enforce which commands are allowed to run 这确保了管理员可以强制执行允许运行的命令
3,Non-stdio server behavior: 非标准输入输出服务器行为:
Remote servers (HTTP, SSE, WebSocket) use URL-based matching when serverUrl entries exist in the allowlist 远程服务器(HTTP、SSE、WebSocket)在允许列表中存在 serverUrl 条目时使用基于 URL 的匹配
If no URL entries exist, remote servers fall back to name-based matching 如果没有 URL 条目,远程服务器会回退到基于名称的匹配
Command restrictions do not apply to remote servers 命令限制不适用于远程服务器
How URL-based restrictions work
基于 URL 的访问限制如何工作
URL patterns support wildcards using * to match any sequence of characters. This is useful for allowing entire domains or subdomains. URL 模式支持使用 * 匹配任意字符序列。这对于允许整个域名或子域名非常有用。
1, Wildcard examples: 通配符示例: mcp.company.com/* - Allow all paths on a specific domain 允许特定域名的所有路径
https://.example.com/ - Allow any subdomain of example.com允许 example.com 的任何子域名
http://localhost:*/* - Allow any port on localhost允许 localhost 的任何端口
2,Remote server behavior: 远程服务器行为:
When the allowlist contains any serverUrl entries, remote servers must match one of those URL patterns 当允许列表包含任何 serverUrl 条目时,远程服务器必须匹配其中的一种 URL 模式
Remote servers cannot pass by name alone when URL restrictions are present 当存在 URL 限制时,远程服务器不能仅凭名称通过
This ensures administrators can enforce which remote endpoints are allowed 这确保了管理员可以强制执行允许哪些远程端点
Example: URL-only allowlist 示例:仅 URL 的允许列表
{
"allowedMcpServers": [
{ "serverUrl": "https://mcp.company.com/*" },
{ "serverUrl": "https://*.internal.corp/*" }
]
}
Result: 结果: HTTP server at mcp.company.com/api: ✅ Allowed (matches URL pattern) (匹配 URL 模式) HTTP server at api.internal.corp/mcp: ✅ Allowed (matches wildcard subdomain)(匹配通配符子域名) HTTP server at external.com/mcp: ❌ Blocked (doesn’t match any URL pattern)不匹配任何 URL 模式) Stdio server with any command: ❌ Blocked (no name or command entries to match) 任何命令的 stdio 服务器: 被阻止(没有名称或命令条目匹配)
Example: Command-only allowlist 示例:仅命令白名单
{
"allowedMcpServers": [
{ "serverCommand": ["npx", "-y", "approved-package"] }
]
}
Result: 结果: Stdio server with ["npx", "-y", "approved-package"]: ✅ Allowed (matches command)(匹配命令)
Stdio server with ["node", "server.js"]: ❌ Blocked (doesn’t match command)(不匹配命令)
HTTP server named “my-api”: ❌ Blocked (no name entries to match) 名为“my-api”的 HTTP 服务器:❌阻止(无名称条目匹配)
Example: Mixed name and command allowlist 示例:混合名称和命令白名单
{
"allowedMcpServers": [
{ "serverName": "github" },
{ "serverCommand": ["npx", "-y", "approved-package"] }
]
}
Result: 结果: Stdio server named “local-tool” with ["npx", "-y", "approved-package"]: ✅ Allowed (matches command) 名称为“local-tool”的 Stdio 服务器被允许(匹配命令)
Stdio server named “local-tool” with ["node", "server.js"]: ❌ Blocked (command entries exist but doesn’t match) 名称为“local-tool”的 Stdio 服务器被 阻止(存在命令条目但不匹配)
Stdio server named “github” with ["node", "server.js"]: ❌ Blocked (stdio servers must match commands when command entries exist) 名称为“github”的 Stdio 服务器被 阻止(当存在命令条目时,stdio 服务器必须与命令匹配)
HTTP server named “github”: ✅ Allowed (matches name) 名为“github”的 HTTP 服务器: 允许(名称匹配)
HTTP server named “other-api”: ❌ Blocked (name doesn’t match) 名为“other-api”的 HTTP 服务器:被阻止(名称不匹配)
Example: Name-only allowlist 示例:仅名称的允许列表
{
"allowedMcpServers": [
{ "serverName": "github" },
{ "serverName": "internal-tool" }
]
}
Result: 结果:
Stdio server named “github” with any command: ✅ Allowed (no command restrictions) 名为“github”的 Stdio 服务器,使用任何命令:允许(无命令限制)
Stdio server named “internal-tool” with any command: ✅ Allowed (no command restrictions) 名为“internal-tool”的 Stdio 服务器,使用任何命令: 允许(无命令限制)
HTTP server named “github”: ✅ Allowed (matches name) 名为“github”的 HTTP 服务器: 允许(名称匹配)
Any server named “other”: ❌ Blocked (name doesn’t match) 任何名为“other”的服务器: 被阻止(名称不匹配)
Allowlist behavior (allowedMcpServers)
白名单行为( allowedMcpServers )
1,undefined (default): No restrictions - users can configure any MCP server undefined (默认):无限制 - 用户可以配置任何 MCP 服务器
2,Empty array []: Complete lockdown - users cannot configure any MCP servers [] 空数组:完全封锁 - 用户无法配置任何 MCP 服务器
3,List of entries: Users can only configure servers that match by name, command, or URL pattern 条目列表:用户只能配置名称、命令或 URL 模式匹配的服务器
Denylist behavior (deniedMcpServers)
拒绝列表行为( deniedMcpServers )
1,undefined (default): No servers are blocked undefined (默认):没有服务器被阻止
2,Empty array []: No servers are blocked 空数组 [] : 没有服务器被阻止
3,List of entries: Specified servers are explicitly blocked across all scopes 条目列表:指定的服务器在所有范围内都被明确阻止
Important notes 重要提示
Option 1 and Option 2 can be combined: If managed-mcp.json exists, it has exclusive control and users cannot add servers. Allowlists/denylists still apply to the managed servers themselves. 选项 1 和选项 2 可以结合使用:如果存在 managed-mcp.json ,它将拥有独占控制权,用户无法添加服务器。允许列表/拒绝列表仍然适用于被管理的服务器本身。
Denylist takes absolute precedence: If a server matches a denylist entry (by name, command, or URL), it will be blocked even if it’s on the allowlist Denylist 具有绝对优先权:如果服务器匹配了 denylist 条目(通过名称、命令或 URL),即使它在 allowlist 中也会被阻止
Name-based, command-based, and URL-based restrictions work together: a server passes if it matches either a name entry, a command entry, or a URL pattern (unless blocked by denylist) 基于名称、基于命令和基于 URL 的限制共同作用:服务器如果匹配名称条目、命令条目或 URL 模式中的任意一个(除非被 denylist 阻止),则通过
When using managed-mcp.json: Users cannot add MCP servers through claude mcp add or configuration files. The allowedMcpServers and deniedMcpServers settings still apply to filter which managed servers are actually loaded. 使用 managed-mcp.json 时:用户无法通过 claude mcp add 或配置文件添加 MCP 服务器。 allowedMcpServers 和 deniedMcpServers 设置仍然适用,用于过滤实际加载哪些管理的服务器
小结: mcp支持3种连接方式
也有3种作用域,如果有敏感凭证,用local
MCP Tool Search可以动态加载工具,而不是预加载所有工具