เชื่อมต่อกับ External Tools ด้วย MCP
Configure MCP servers เพื่อขยาย agent ของคุณด้วย external tools ครอบคลุม transport types, tool search สำหรับ tool sets ขนาดใหญ่, authentication, และ error handling
Model Context Protocol (MCP) คือมาตรฐานเปิดสำหรับเชื่อมต่อ AI agents กับ external tools และ data sources ด้วย MCP agent ของคุณสามารถ query ฐานข้อมูล, ผสานรวมกับ APIs เช่น Slack และ GitHub, และเชื่อมต่อกับบริการอื่นๆ โดยไม่ต้องเขียน custom tool implementations
หน้านี้ครอบคลุม MCP configuration สำหรับ Agent SDK สำหรับการเพิ่ม MCP servers ไปยัง Claude Code CLI ดู MCP installation scopes
Quickstart
ตัวอย่างนี้เชื่อมต่อกับ Claude Code documentation MCP server โดยใช้ HTTP transport และใช้ wildcard ใน allowedTools เพื่ออนุญาต tools ทั้งหมดจาก server:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Use the docs MCP server to explain what hooks are in Claude Code",
options: {
mcpServers: {
"claude-code-docs": {
type: "http",
url: "https://code.claude.com/docs/mcp"
}
},
allowedTools: ["mcp__claude-code-docs__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
options = ClaudeAgentOptions(
mcp_servers={
"claude-code-docs": {
"type": "http",
"url": "https://code.claude.com/docs/mcp",
}
},
allowed_tools=["mcp__claude-code-docs__*"],
)
async for message in query(
prompt="Use the docs MCP server to explain what hooks are in Claude Code",
options=options,
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
เพิ่ม MCP Server
ใน code
ส่ง MCP servers โดยตรงใน option mcpServers:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "List files in my project",
options: {
mcpServers: {
filesystem: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
},
allowedTools: ["mcp__filesystem__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
options = ClaudeAgentOptions(
mcp_servers={
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/me/projects",
],
}
},
allowed_tools=["mcp__filesystem__*"],
)
async for message in query(prompt="List files in my project", options=options):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
จาก config file
สร้างไฟล์ .mcp.json ที่ project root ไฟล์ถูก pick up เมื่อ setting source project ถูกเปิดใช้งาน:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
}
}
Allow MCP Tools
MCP tools ต้องการ permission อย่างชัดเจนก่อนที่ Claude จะสามารถใช้ได้
Tool naming convention
MCP tools ใช้รูปแบบการตั้งชื่อ mcp__<server-name>__<tool-name> ตัวอย่างเช่น GitHub server ชื่อ "github" ที่มี tool list_issues กลายเป็น mcp__github__list_issues
Auto-approve ด้วย allowedTools
ใช้ allowedTools เพื่อ auto-approve MCP tools เฉพาะเจาะจง:
const _ = {
options: {
mcpServers: {
// servers ของคุณ
},
allowedTools: [
"mcp__github__*", // Tools ทั้งหมดจาก github server
"mcp__db__query", // เฉพาะ tool query จาก db server
"mcp__slack__send_message" // เฉพาะ send_message จาก slack server
]
}
};
ใช้ allowedTools ดีกว่า permission modes สำหรับ MCP access permissionMode: "acceptEdits" ไม่ auto-approve MCP tools (เฉพาะ file edits และ filesystem Bash commands) permissionMode: "bypassPermissions" auto-approve MCP tools แต่ยังปิดใช้งาน safety prompts อื่นๆ ด้วย Wildcard ใน allowedTools ให้ permission เฉพาะ MCP server ที่คุณต้องการและไม่มีอะไรเพิ่มเติม
Transport Types
stdio servers
Local processes ที่สื่อสารผ่าน stdin/stdout ใช้สำหรับ MCP servers ที่รันบนเครื่องเดียวกัน:
const _ = {
options: {
mcpServers: {
github: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
}
},
allowedTools: ["mcp__github__list_issues", "mcp__github__search_issues"]
}
};
options = ClaudeAgentOptions(
mcp_servers={
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
}
},
allowed_tools=["mcp__github__list_issues", "mcp__github__search_issues"],
)
HTTP/SSE servers
ใช้ HTTP หรือ SSE สำหรับ cloud-hosted MCP servers และ remote APIs:
const _ = {
options: {
mcpServers: {
"remote-api": {
type: "sse",
url: "https://api.example.com/mcp/sse",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`
}
}
},
allowedTools: ["mcp__remote-api__*"]
}
};
SDK MCP servers
กำหนด custom tools โดยตรงใน application code แทนการรัน server process แยกต่างหาก ดู custom tools guide สำหรับ implementation details
MCP Tool Search
เมื่อคุณมี MCP tools จำนวนมากที่ configure ไว้ tool definitions สามารถใช้ส่วนสำคัญของ context window tool search แก้ปัญหานี้โดยไม่นำ tool definitions ไปใส่ใน context และโหลดเฉพาะที่ Claude ต้องการสำหรับแต่ละ turn
Tool search ถูกเปิดใช้งาน default ดู Tool search สำหรับ configuration options
Authentication
ส่ง credentials ผ่าน environment variables
ใช้ field env เพื่อส่ง API keys, tokens, และ credentials อื่นๆ ไปยัง MCP server:
options = ClaudeAgentOptions(
mcp_servers={
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
}
},
allowed_tools=["mcp__github__list_issues"],
)
HTTP headers สำหรับ remote servers
สำหรับ HTTP และ SSE servers ส่ง authentication headers โดยตรงใน server configuration:
options = ClaudeAgentOptions(
mcp_servers={
"secure-api": {
"type": "http",
"url": "https://api.example.com/mcp",
"headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"},
}
},
allowed_tools=["mcp__secure-api__*"],
)
OAuth2 authentication
MCP specification รองรับ OAuth 2.1 SDK ไม่จัดการ OAuth flows โดยอัตโนมัติ แต่คุณสามารถส่ง access tokens ผ่าน headers หลังจาก complete OAuth flow ใน application ของคุณ:
# หลังจาก complete OAuth flow ใน app ของคุณ
access_token = await get_access_token_from_oauth_flow()
options = ClaudeAgentOptions(
mcp_servers={
"oauth-api": {
"type": "http",
"url": "https://api.example.com/mcp",
"headers": {"Authorization": f"Bearer {access_token}"},
}
},
allowed_tools=["mcp__oauth-api__*"],
)
ตัวอย่าง
List issues จาก repository
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "List the 3 most recent issues in anthropics/claude-code",
options: {
mcpServers: {
github: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
}
},
allowedTools: ["mcp__github__list_issues"]
}
})) {
if (message.type === "system" && message.subtype === "init") {
console.log("MCP servers:", message.mcp_servers);
}
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
Query ฐานข้อมูล
import asyncio
import os
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
connection_string = os.environ["DATABASE_URL"]
options = ClaudeAgentOptions(
mcp_servers={
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
connection_string,
],
}
},
allowed_tools=["mcp__postgres__query"],
)
async for message in query(
prompt="How many users signed up last week? Break it down by day.",
options=options,
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
Error Handling
SDK ส่ง system message ที่มี subtype init ที่เริ่มต้นของแต่ละ query message นี้รวม connection status สำหรับแต่ละ MCP server:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Process data",
options: {
mcpServers: {
"data-processor": dataServer
}
}
})) {
if (message.type === "system" && message.subtype === "init") {
const failedServers = message.mcp_servers.filter((s) => s.status !== "connected");
if (failedServers.length > 0) {
console.warn("Failed to connect:", failedServers);
}
}
}
Troubleshooting
Server แสดงสถานะ "failed"
สาเหตุทั่วไป:
- Missing environment variables: ตรวจสอบว่า required tokens และ credentials ถูกตั้งค่า
- Server ไม่ได้ install: สำหรับ
npxcommands ตรวจสอบว่า package มีอยู่และ Node.js อยู่ใน PATH - Invalid connection string: สำหรับ database servers ตรวจสอบรูปแบบ connection string
- Network issues: สำหรับ remote HTTP/SSE servers ตรวจสอบว่า URL เข้าถึงได้
Tools ไม่ถูกเรียก
หาก Claude เห็น tools แต่ไม่ใช้พวกมัน ตรวจสอบว่าคุณให้ permission ด้วย allowedTools:
const _ = {
options: {
mcpServers: {
// servers ของคุณ
},
allowedTools: ["mcp__servername__*"] // Auto-approve calls จาก server นี้
}
};
เอกสารที่เกี่ยวข้อง
- Custom tools guide: สร้าง MCP server ของตัวเองที่รัน in-process กับ SDK application ของคุณ
- Permissions: ควบคุม MCP tools ที่ agent ของคุณสามารถใช้ได้
- TypeScript SDK reference: API reference ครบถ้วนรวมถึง MCP configuration options
- Python SDK reference: API reference ครบถ้วนรวมถึง MCP configuration options
- MCP server directory: เรียกดู MCP servers ที่ใช้ได้สำหรับ databases, APIs, และอื่นๆ