惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Cyberwarzone
Cyberwarzone
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
小众软件
小众软件
Recent Announcements
Recent Announcements
博客园 - 三生石上(FineUI控件)
Security Archives - TechRepublic
Security Archives - TechRepublic
W
WeLiveSecurity
Cloudbric
Cloudbric
博客园 - 司徒正美
美团技术团队
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
PCI Perspectives
PCI Perspectives
宝玉的分享
宝玉的分享
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Last Week in AI
Last Week in AI
S
Schneier on Security
N
News | PayPal Newsroom
B
Blog RSS Feed
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
S
Secure Thoughts
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tenable Blog
S
Securelist
L
LangChain Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
InfoQ
H
Heimdal Security Blog
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
C
Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Deep Dive into Open Agent SDK (Part 3): MCP Integration in Practice
NEE · 2026-04-27 · via DEV Community

The previous article looked at the SDK's 34 built-in tools — file read/write, Bash execution, code search — covering common development scenarios. But an Agent's capabilities can't rely solely on built-in tools. You need to connect to databases, call enterprise APIs, and operate internal systems. These require a standardized integration approach.

MCP (Model Context Protocol) is designed for exactly this. This article examines how Open Agent SDK uses the MCP protocol to bring external tools into the Agent Loop.

What Is the MCP Protocol

MCP is an open protocol proposed by Anthropic that defines communication standards between LLM applications and external tools/data sources. The concept:

  • Tool side (MCP Server) exposes a set of tools, each with a name, description, and input schema
  • Calling side (MCP Client) discovers tools, invokes them, and gets results through a standard protocol
  • Communication is based on JSON-RPC with swappable transports

Why does an Agent need this? Because it's impossible to build all tools into the SDK. With MCP, anyone can write an MCP Server (e.g., @modelcontextprotocol/server-filesystem), and any Agent can connect — no SDK code changes needed, no adapter to write, just one line of configuration.

Open Agent SDK's MCP integration has two paths:

  1. External MCP servers: Connect to third-party MCP Servers via stdio/HTTP/SSE, running the full MCP protocol
  2. In-process MCP servers: Use InProcessMCPServer to wrap SDK tools as an MCP Server with zero protocol overhead

Let's examine each.

Five Transport Configurations

The SDK uses the McpServerConfig enum to unify all transport methods:

public enum McpServerConfig: Sendable, Equatable {
    case stdio(McpStdioConfig)       // Child process stdin/stdout
    case sse(McpTransportConfig)     // Server-Sent Events
    case http(McpTransportConfig)    // HTTP POST
    case sdk(McpSdkServerConfig)     // In-process, zero overhead
    case claudeAIProxy(McpClaudeAIProxyConfig) // ClaudeAI proxy
}

Enter fullscreen mode Exit fullscreen mode

Stdio: Launching Child Processes

The most common approach. The Agent launches a child process and exchanges JSON-RPC messages via stdin/stdout. Suitable for MCP Servers written in Node.js/Python:

let servers: [String: McpServerConfig] = [
    "filesystem": .stdio(McpStdioConfig(
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
    )),
    "git": .stdio(McpStdioConfig(
        command: "uvx",
        args: ["mcp-server-git"],
        env: ["GIT_REPO_PATH": "/my/repo"]
    ))
]

Enter fullscreen mode Exit fullscreen mode

MCPStdioTransport internally uses Foundation's Process to launch child processes and FileDescriptor for low-level I/O. A few details:

  • Command resolution: If the command isn't an absolute path, it's looked up via which first. Falls back to treating it as a file path if not found
  • Message delimiting: Each JSON-RPC message is delimited by newlines, with CRLF support
  • Security filtering: CODEANY_API_KEY is not passed to child processes by default unless explicitly specified in env
  • Reconnection: MCPClient is configured with up to 2 automatic retries, initial interval 1 second, exponential backoff up to max 10 seconds

SSE and HTTP: Connecting to Remote Services

Remote MCP Servers connect via HTTP, in two modes:

// SSE mode (long connection, server push)
let sseServer: [String: McpServerConfig] = [
    "remote-tools": .sse(McpTransportConfig(
        url: "https://mcp.example.com/sse",
        headers: ["Authorization": "Bearer token123"]
    ))
]

// HTTP mode (request-response)
let httpServer: [String: McpServerConfig] = [
    "api-tools": .http(McpTransportConfig(
        url: "https://mcp.example.com/api"
    ))
]

Enter fullscreen mode Exit fullscreen mode

SSE is for scenarios requiring server push; HTTP for simple request-response. Both use HTTPClientTransport internally, differing in the streaming parameter. McpSseConfig and McpHttpConfig are actually type aliases for McpTransportConfig:

public typealias McpSseConfig = McpTransportConfig
public typealias McpHttpConfig = McpTransportConfig

Enter fullscreen mode Exit fullscreen mode

SDK: In-Process Zero Overhead

No network protocol at all — tools are registered directly in-process. Covered in detail in section six below.

ClaudeAI Proxy

Connects to ClaudeAI's proxy endpoint, using server ID for authentication:

let proxyServer: [String: McpServerConfig] = [
    "claude-tools": .claudeAIProxy(McpClaudeAIProxyConfig(
        url: "https://claudeai.example.com/proxy",
        id: "server-abc-123"
    ))
]

Enter fullscreen mode Exit fullscreen mode

Internally, this is just HTTP transport with an added X-ClaudeAI-Server-ID header.

Connection Flow: From Configuration to Tool Pool

How does the Agent merge MCP tools into its own tool pool? Tracing from assembleFullToolPool():

func assembleFullToolPool() async -> ([ToolProtocol], MCPClientManager?) {
    let baseTools = options.tools ?? []

    guard let mcpServers = options.mcpServers, !mcpServers.isEmpty else {
        return (baseTools, nil)
    }

    // Step 1: Separate SDK configs from external configs
    let (sdkTools, externalServers) = await Self.processMcpConfigs(mcpServers)

    // Step 2: Connect to external MCP servers
    var externalTools: [ToolProtocol] = []
    var manager: MCPClientManager? = nil

    if !externalServers.isEmpty {
        let mcpManager = MCPClientManager()
        await mcpManager.connectAll(servers: externalServers)
        externalTools = await mcpManager.getMCPTools()
        manager = mcpManager
    }

    // Step 3: Merge all tools
    let allMCPTools = sdkTools + externalTools
    let pool = assembleToolPool(
        baseTools: getAllBaseTools(tier: .core) + getAllBaseTools(tier: .specialist),
        customTools: baseTools,
        mcpTools: allMCPTools,
        allowed: options.allowedTools,
        disallowed: options.disallowedTools
    )

    return (pool, manager)
}

Enter fullscreen mode Exit fullscreen mode

Three steps:

1. Separate configurations. processMcpConfigs() splits .sdk configs from external configs (stdio/sse/http). SDK configs directly extract tools from InProcessMCPServer, adding namespace prefixes via SdkToolWrapper; external configs are left for MCPClientManager.

2. Connect to external servers. MCPClientManager is an actor that uses withTaskGroup to connect to all servers concurrently. Each connection goes through four steps:

Create Transport → Start Connection → MCP Handshake (initialize) → listTools() to discover tools

Enter fullscreen mode Exit fullscreen mode

Discovered tools are wrapped as MCPToolDefinition — a struct conforming to ToolProtocol. Tool names follow the mcp__{serverName}__{toolName} format to avoid conflicts with built-in tools. For example, the read_file tool on the filesystem server becomes mcp__filesystem__read_file.

3. Assemble tool pool. MCP tools merge with built-in and custom tools, pass through allowedTools/disallowedTools filtering, and form the final tool pool. The LLM sees the filtered complete tool list.

Complete end-to-end usage code:

let agent = createAgent(options: AgentOptions(
    apiKey: "sk-...",
    model: "claude-sonnet-4-6",
    permissionMode: .bypassPermissions,
    mcpServers: [
        "filesystem": .stdio(McpStdioConfig(
            command: "npx",
            args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
        ))
    ]
))

// Agent Loop auto-connects MCP servers, discovers tools, merges into tool pool on startup
let result = await agent.prompt("List all files in /tmp and read the first one")

Enter fullscreen mode Exit fullscreen mode

Runtime Management

MCP servers aren't just connect-and-forget. During runtime, you may need to check status, reconnect, toggle, or even dynamically swap server sets. The SDK provides four methods.

Check Status: mcpServerStatus()

let status = await agent.mcpServerStatus()
for (name, info) in status {
    print("\(name): \(info.status.rawValue)")  // connected / failed / pending / disabled / needsAuth
    print("  tools: \(info.tools)")             // ["read_file", "write_file", ...]
    if let error = info.error {
        print("  error: \(error)")
    }
}

Enter fullscreen mode Exit fullscreen mode

McpServerStatus has five states (aligned with the TypeScript SDK):

State Meaning
connected Connected, tools available
failed Connection failed
pending Connecting
disabled Disabled by user
needsAuth Requires authentication

Reconnect: reconnectMcpServer()

Manually reconnect a server after network issues or server restarts:

try await agent.reconnectMcpServer(name: "filesystem")

Enter fullscreen mode Exit fullscreen mode

Implementation: disconnect old connection → clean up state → re-run the connection flow with the initial config. MCPClientManager saves the original config at first connection (originalConfigs), using it directly for reconnection.

Toggle: toggleMcpServer()

Temporarily disable a server (disconnect but keep config), can be re-enabled later:

// Disable
try await agent.toggleMcpServer(name: "filesystem", enabled: false)

// Re-enable
try await agent.toggleMcpServer(name: "filesystem", enabled: true)

Enter fullscreen mode Exit fullscreen mode

Dynamic Replacement: setMcpServers()

Replace the entire MCP server set at runtime. The SDK diffs: new ones get connected, removed ones get disconnected, changed ones get reconnected:

let result = try await agent.setMcpServers([
    "filesystem": .stdio(McpStdioConfig(
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-filesystem", "/data"]
    )),
    "database": .stdio(McpStdioConfig(
        command: "python3",
        args: ["-m", "my_db_server"]
    ))
])

print("Added: \(result.added)")      // ["database"]
print("Removed: \(result.removed)")  // Previously existing but now absent
print("Errors: \(result.errors)")    // Failed connections

Enter fullscreen mode Exit fullscreen mode

MCPClientManager.setServers() diff logic:

public func setServers(_ servers: [String: McpServerConfig]) async -> McpServerUpdateResult {
    let existingNames = Set(originalConfigs.keys)
    let newNames = Set(servers.keys)

    let addedNames = newNames.subtracting(existingNames)
    let removedNames = existingNames.subtracting(newNames)

    // Changed configs are treated as remove + add
    let changedNames = newNames.intersection(existingNames).filter { name in
        originalConfigs[name] != servers[name]
    }

    let effectiveAdded = addedNames.union(changedNames)
    // ...execute connections and disconnections
}

Enter fullscreen mode Exit fullscreen mode

Removes unneeded servers first, then connects new and changed ones. Changed servers are completely rebuilt, not hot-updated. This matters for long-running Agent applications — you can adjust MCP configuration without restarting the Agent.

MCP Resources: Beyond Tools

The MCP protocol includes resources in addition to tools. Tools "do things"; resources "read data" — e.g., a database MCP Server can expose a query tool alongside a tables resource letting the Agent see which tables exist.

The SDK has two resource-related tools built in: ListMcpResources and ReadMcpResource.

ListMcpResources

Lists available resources from all connected MCP servers:

// Tool description as seen by LLM:
// "List available resources from connected MCP servers.
//  Resources can include files, databases, and other data sources."

// Optional parameter: server — filter by server name

Enter fullscreen mode Exit fullscreen mode

Internal implementation queries each connection via the MCPResourceProvider protocol:

public protocol MCPResourceProvider: Sendable {
    func listResources() async -> [MCPResourceItem]?
    func readResource(uri: String) async throws -> MCPReadResult
}

Enter fullscreen mode Exit fullscreen mode

Resources are represented as MCPResourceItem — with name, description, and URI.

ReadMcpResource

Reads the content of a specified URI resource:

// LLM sees the tool:
// "Read a specific resource from an MCP server."
// Parameters: server (server name), uri (resource URI)

Enter fullscreen mode Exit fullscreen mode

Both tools are read-only, accessing connection info through ToolContext.mcpConnections — no global variables, thread-safe.

In-Process MCP: InProcessMCPServer

InProcessMCPServer is a unique design in the SDK. It lets you create tools with defineTool(), then wrap them as an MCP Server — but without actually running the MCP protocol.

Why? Because sometimes you just want to add your own tools to the Agent's tool pool without cross-process communication. Calling a function directly is far more efficient than going through JSON-RPC serialization.

Basic Usage

// Create tool with defineTool
struct WeatherInput: Codable {
    let city: String
}

let weatherTool = defineTool(
    name: "get_weather",
    description: "Get the current weather for a given city.",
    inputSchema: [
        "type": "object",
        "properties": [
            "city": ["type": "string", "description": "The city name"]
        ],
        "required": ["city"]
    ],
    isReadOnly: true
) { (input: WeatherInput, context: ToolContext) -> String in
    let data: [String: String] = [
        "Beijing": "Sunny, 22C",
        "Tokyo": "Cloudy, 18C",
    ]
    return data[input.city] ?? "No data for \(input.city)"
}

// Wrap as InProcessMCPServer
let server = InProcessMCPServer(
    name: "weather",       // Tool name will be mcp__weather__get_weather
    version: "1.0.0",
    tools: [weatherTool],
    cwd: "/tmp"
)

// Generate config via asConfig(), inject into Agent
let agent = createAgent(options: AgentOptions(
    apiKey: "sk-...",
    model: "claude-sonnet-4-6",
    mcpServers: ["weather": await server.asConfig()]
))

Enter fullscreen mode Exit fullscreen mode

Internal Implementation

InProcessMCPServer is an actor with two working modes:

SDK internal mode (common): When processMcpConfigs() detects a .sdk config, it calls server.getTools() directly and adds namespace prefixes via SdkToolWrapper. Throughout this process, the tool's call() method is invoked directly with zero serialization overhead:

private struct SdkToolWrapper: ToolProtocol, Sendable {
    let serverName: String
    let innerTool: ToolProtocol

    var name: String { "mcp__\(serverName)__\(innerTool.name)" }

    func call(input: Any, context: ToolContext) async -> ToolResult {
        return await innerTool.call(input: input, context: context)
    }
}

Enter fullscreen mode Exit fullscreen mode

Note that SdkToolWrapper's call() directly forwards to innerTool — no JSON-RPC, no Value conversion, just a direct function call.

External client mode: If an external MCP Client wants to connect in, createSession() creates an InMemoryTransport pair, running the full MCP handshake. Protocol overhead exists only in this scenario:

public func createSession() async throws -> (Server, InMemoryTransport) {
    let mcpServer = await getOrCreateMCPServer()
    let session = await mcpServer.createSession()
    let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair()
    try await session.start(transport: serverTransport)
    return (session, clientTransport)
}

Enter fullscreen mode Exit fullscreen mode

InProcessMCPServer internally maintains an MCPServer instance (lazy-loaded). When registering tools, each ToolProtocol's call() is wrapped as an MCP handler closure — handling parameter format conversion ([String: Value] to [String: Any]), building ToolContext, and processing error results.

Caveats

  • Naming restriction: Server name cannot contain __ (double underscore), as it would conflict with the namespace prefix mcp__{server}__{tool}. A precondition check exists in the constructor.
  • Error handling: When a tool returns isError: true, the MCP layer throws ToolExecutionError, causing the MCP protocol to return isError: true.
  • Tool registration failure: Triggers assertionFailure, indicating a code bug (e.g., duplicate tool names).

Complete Example: Multi-Tool MCP Server

This is the core of the AdvancedMCPExample, demonstrating multi-tool registration and error handling:

// Weather tool — returns String
let weatherTool = defineTool(
    name: "get_weather",
    description: "Get the current weather for a given city.",
    inputSchema: [
        "type": "object",
        "properties": [
            "city": ["type": "string", "description": "The city name"]
        ],
        "required": ["city"]
    ],
    isReadOnly: true
) { (input: WeatherInput, context: ToolContext) -> String in
    let data: [String: String] = [
        "Beijing": "Sunny, 22C, humidity 45%",
        "Tokyo": "Cloudy, 18C, humidity 65%",
    ]
    return data[input.city] ?? "No data for \(input.city)"
}

// Email validation — returns ToolExecuteResult with error handling
let validationTool = defineTool(
    name: "validate_email",
    description: "Validate an email address.",
    inputSchema: [
        "type": "object",
        "properties": [
            "email": ["type": "string", "description": "The email address"]
        ],
        "required": ["email"]
    ],
    isReadOnly: true
) { (input: ValidateInput, context: ToolContext) -> ToolExecuteResult in
    if !input.email.contains("@") {
        return ToolExecuteResult(
            content: "Invalid email: '\(input.email)' missing '@'",
            isError: true
        )
    }
    return ToolExecuteResult(content: "Email '\(input.email)' is valid.", isError: false)
}

// Package as MCP server
let utilityServer = InProcessMCPServer(
    name: "utility",
    version: "1.0.0",
    tools: [weatherTool, validationTool],
    cwd: "/tmp"
)

// Create Agent
let agent = createAgent(options: AgentOptions(
    apiKey: apiKey,
    model: "claude-sonnet-4-6",
    systemPrompt: "You have weather and email validation tools.",
    permissionMode: .bypassPermissions,
    mcpServers: ["utility": await utilityServer.asConfig()]
))

// LLM will automatically call mcp__utility__get_weather or mcp__utility__validate_email
let result = await agent.prompt("Check weather in Tokyo and validate test@example.com")
print(result.text)

Enter fullscreen mode Exit fullscreen mode

When a tool returns an error, the Agent doesn't crash. The error message is fed back to the LLM, which sees it and adjusts strategy — for example, telling the user the email format is invalid.

Practical Recommendations

Choose the right transport. Use InProcessMCPServer (SDK mode) for in-process tools, stdio for external local tools, and HTTP/SSE for remote tools. Don't use stdio to connect to remote services or HTTP for local CLI tools.

Naming conventions. MCP tool names follow the mcp__{server}__{tool} three-segment format. Keep server names short and meaningful, avoiding double underscores. filesystem is better than fs-tools-v2, because the LLM can directly guess the meaning of mcp__filesystem__read_file.

Error tolerance. MCPClientManager connection failures don't crash the Agent — failed servers get their status marked as error, contributing zero tools. The Agent Loop continues running, just without those tools. Design your system with the same principle: degrade gracefully when external services are unavailable, don't crash entirely.

Use runtime management. Long-running Agent applications should check mcpServerStatus() after startup, retrying failures with reconnectMcpServer(). Use setMcpServers() for dynamic adjustments rather than rebuilding the Agent.


Deep Dive into Open Agent SDK (Swift) Series:

GitHub: terryso/open-agent-sdk-swift