Transport Type | Scenario | Description |
STDIO | Local tool | Communicate with local processes through standard input and output. |
HTTP/SSE | Remote service | Communicate with remote services through HTTP streaming or Server-Sent Events. |
SDK MCP | IDE/SDK integration | MCP server registered by an external SDK (such as an IDE extension) |
mcpServers supports two configuration methods:mcpServers option to configure MCP servers. The configuration supports STDIO, HTTP, and SSE transport types.import { query } from '@tencent-ai/agent-sdk';const result = query({prompt: 'Analyze my project structure',options: {mcpServers: {'my-tools': {type: 'stdio',command: 'node',args: ['./mcp-server.js'],env: {NODE_ENV: 'production'}},'api-server': {type: 'http',url: 'https://api.example.com/mcp',headers: {'Authorization': 'Bearer your-token'}},'sse-server': {type: 'sse',url: 'https://events.example.com/mcp/sse',headers: {'X-API-Key': 'your-api-key'}}}}});
from codebuddy_agent_sdk import queryresult = query(prompt='Analyze my project structure',options={'mcp_servers': {'my-tools': {'type': 'stdio','command': 'python','args': ['-m', 'my_mcp_server'],'env': {'PYTHONPATH': '/path/to/tools'}},'api-server': {'type': 'http','url': 'https://api.example.com/mcp','headers': {'Authorization': 'Bearer your-token'}},'sse-server': {'type': 'sse','url': 'https://events.example.com/mcp/sse','headers': {'X-API-Key': 'your-api-key'}}}})
--mcp-config parameter.import { query } from '@tencent-ai/agent-sdk';const result = query({prompt: 'Analyze my project structure',options: {mcpServers: './mcp-config.json'}});
from codebuddy_agent_sdk import queryresult = query(prompt='Analyze my project structure',options={'mcp_servers': './mcp-config.json'})
mcp-config.json):{"mcpServers": {"my-tools": {"type": "stdio","command": "node","args": ["./mcp-server.js"]}}}
type: 'sdk') are not supported. SDK MCP servers are available only in the object format.{type: 'stdio',command: 'python', // Executable file or commandargs: ['-m', 'my_mcp_server'], // Command-line argumentsenv: { // Environment variablesPYTHONPATH: '/path/to/tools',DEBUG: 'true'}}
// Python MCP server{type: 'stdio',command: 'python',args: ['-m', 'fastmcp']}// Node.js MCP server{type: 'stdio',command: 'node',args: ['./server.js']}// Local binary file{type: 'stdio',command: '/usr/local/bin/my-tool',args: ['--config', '/etc/config.yaml']}
{type: 'http',url: 'https://mcp.example.com/api/v1',headers: {'Authorization': 'Bearer your-token','Content-Type': 'application/json'}}
{type: 'sse',url: 'https://events.example.com/mcp/sse',headers: {'Authorization': 'Bearer your-token','X-API-Version': 'v1'}}
canUseTool callback, you can determine which tools can be used.type PermissionMode =| 'default' // Ask the user| 'acceptEdits' // Accept automatic edits.| 'bypassPermissions' // Skip permission checks (not recommended for production environments)| 'plan'; // Plan-only mode.const result = query({prompt: 'Process data',options: {permissionMode: 'acceptEdits',canUseTool?: (toolCall) => {// Custom permission check logicif (toolCall.name === 'dangerous_operation') {return false;}return true;}}});
options: {canUseTool: (toolCall) => {// Block tools from specific servers.if (toolCall.name.startsWith('mcp__restricted')) {return false;}// Allow specific tools.if (toolCall.name === 'mcp__github__list_issues') {return true;}// Ask by default.return null;}}
const result = query({prompt: `Using the available MCP tools, complete these tasks:1. Query the database for recent transactions2. Analyze the results3. Generate a summary report`,options: {mcpServers: {'database': {type: 'stdio',command: 'python',args: ['-m', 'db_mcp_server']}}}});for await (const message of result) {if (message.type === 'tool_use') {console.log(`Tool: ${message.name}`);console.log(`Arguments: ${JSON.stringify(message.input)}`);}}
for await (const message of result) {if (message.type === 'content') {console.log('Agent Response:', message.text);} else if (message.type === 'tool_use') {console.log(`Executing: ${message.name}`);} else if (message.type === 'tool_result') {console.log('Tool Result:', message.content);}}
from fastmcp import FastMCPmcp = FastMCP('database')@mcp.tool()def query_database(sql: str) -> str:"""Execute a SQL query and return results"""# Implement the Database Query Logicreturn f"Query results for: {sql}"@mcp.tool()def get_schema(table_name: str) -> str:"""Get the schema of a specific table"""# Return the Table Schemareturn f"Schema for: {table_name}"if __name__ == '__main__':mcp.run()
import { query } from '@tencent-ai/agent-sdk';async function analyzeData() {const result = query({prompt: `I need to analyze our user activity data.1. First, check the schema of the users table2. Query for users active in the last 7 days3. Provide insights based on the results`,options: {mcpServers: {'database': {type: 'stdio',command: 'python',args: ['-m', 'db_mcp_server'],env: {DATABASE_URL: process.env.DATABASE_URL}}},permissionMode: 'acceptEdits'}});for await (const message of result) {if (message.type === 'content') {console.log('Analysis:', message.text);}}}analyzeData().catch(console.error);
from codebuddy_agent_sdk import queryimport osasync def analyze_data():result = query(prompt="""I need to analyze our user activity data.1. First, check the schema of the users table2. Query for users active in the last 7 days3. Provide insights based on the results""",options={'mcp_servers': {'database': {'type': 'stdio','command': 'python','args': ['-m', 'db_mcp_server'],'env': {'DATABASE_URL': os.environ.get('DATABASE_URL')}}},'permission_mode': 'acceptEdits'})async for message in result:if message.get('type') == 'content':print('Analysis:', message.get('text'))# Example: Run the Sampleimport asyncioasyncio.run(analyze_data())
from fastmcp import FastMCPimport httpximport osmcp = FastMCP('api-gateway')async def call_api(method: str, path: str, **kwargs):"""Helper to call APIs with authentication"""headers = kwargs.pop('headers', {})headers['Authorization'] = f"Bearer {os.environ.get('API_TOKEN')}"async with httpx.AsyncClient() as client:response = await client.request(method,f"https://api.example.com{path}",headers=headers,**kwargs)return response.json()@mcp.tool()async def get_github_repos(username: str) -> dict:"""Get GitHub repositories for a user"""return await call_api('GET', f'/github/users/{username}/repos')@mcp.tool()async def search_issues(query: str, labels: list[str] = None) -> dict:"""Search for issues in GitHub"""params = {'q': query}if labels:params['labels'] = ','.join(labels)return await call_api('GET', '/github/search/issues', params=params)@mcp.tool()async def create_slack_message(channel: str, text: str) -> dict:"""Send a message to Slack"""return await call_api('POST','/slack/chat.postMessage',json={'channel': channel, 'text': text})if __name__ == '__main__':mcp.run()
import { query } from '@tencent-ai/agent-sdk';async function searchAndNotify() {const result = query({prompt: `1. Search for open issues labeled "bug" and "critical"2. Get my GitHub repositories3. Send a summary to the #dev-team Slack channel`,options: {mcpServers: {'api-gateway': {type: 'http',url: 'https://mcp-gateway.example.com/api',headers: {'X-API-Key': process.env.API_GATEWAY_KEY,'X-Request-ID': `req-${Date.now()}`}}},permissionMode: 'acceptEdits'}});for await (const message of result) {console.log(message);}}
import { query } from '@tencent-ai/agent-sdk';async function monitorSystem() {const result = query({prompt: 'Monitor system metrics and alert if any threshold is exceeded',options: {mcpServers: {'monitoring': {type: 'sse',url: 'https://monitor.example.com/mcp/events',headers: {'Authorization': `Bearer ${process.env.MONITOR_TOKEN}`,'X-Client-ID': 'codebuddy-sdk'}}}}});for await (const message of result) {if (message.type === 'content') {console.log('Alert:', message.text);}}}
import { query } from '@tencent-ai/agent-sdk';const result = query({prompt: 'Use my MCP tools',options: {mcpServers: {'my-tool': {type: 'stdio',command: 'python',args: ['-m', 'my_mcp_server']}}}});for await (const message of result) {// Check the MCP server status during initialization.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);}}// Handle execution errors.if (message.type === 'result' && message.subtype === 'error_during_execution') {console.error('Tool execution failed:', message);}}
from codebuddy_agent_sdk import queryresult = query(prompt='Use my MCP tools',options={'mcp_servers': {'my-tool': {'type': 'stdio','command': 'python','args': ['-m', 'my_mcp_server']}}})async for message in result:# Check the MCP server status during initialization.if message.get('type') == 'system' and message.get('subtype') == 'init':failed_servers = [s for s in message.get('mcp_servers', [])if s.get('status') != 'connected']if failed_servers:print(f'Failed to connect: {failed_servers}')# Handle Execution Errorsif message.get('type') == 'result' and message.get('subtype') == 'error_during_execution':print('Tool execution failed:', message)
Was this page helpful?
You can also Contact sales or Submit a Ticket for help.
Help us improve! Rate your documentation experience in 5 mins.
Feedback