Skip to main content
MCP (Model Context Protocol) is an open protocol for AI Agents to invoke external tools. The SDK lets you define MCP Servers and equip your Agent with tools; the underlying CLI handles connection management, tool discovery, and other runtime work.

Architecture Overview

  • In-Process: The tool is a JS function running in your own process. The McpServer instance communicates with the CLI via the SDK’s control channel without spawning an additional child process.
  • External: You declare a child process or remote URL in the configuration; the CLI handles connection, discovery, and invocation.

Three Integration Methods

All three methods can be mixed — register multiple servers of different types in the same query().
In-process tools are the most straightforward extension method: define a regular async function, add a Zod schema, and it becomes callable by the Agent.

30-Second Getting Started

tool() Full Signature

Annotations Actually Consumed

The three fields below are consumed by the SDK and returned to the host via mcpServerStatus().tools[i].annotations:
Note that host-side field names drop the Hint suffix: readOnlyHintannotations.readOnly, and so on. The annotations object only contains fields that were explicitly set. ⚠️ These fields do NOT affect auto-mode permission decisions. CLI treats server-declared annotations as unverifiable advisory metadata (servers can freely under- or over-declare) and intentionally keeps them out of the permission pipeline — admitting them would launder authority for the server’s self-assessment. To hard-block specific tools, use the allowedTools allowlist or hooks — annotations are for host-side identification (mcpServerStatus) and TUI display only.
idempotentHint and title are not currently supported — passing them won’t error, but the SDK won’t consume them or return them to the host. If your application needs this information, maintain the mapping yourself on the host side.

CallToolResult Structure

Use isError: true for operational failures instead of throwing exceptions — exceptions will terminate the entire tool call and the AI won’t get information; isError lets the AI know “this call failed, please try another approach.”

createSdkMcpServer() Full Signature

The return value is shaped like { type: 'sdk', name, instance } and can be directly placed into options.mcpServers.
⚠️ Do not reuse the same server config across multiple query() calls: Each query binds an independent transport. Reusing the same config has no side effects, but you won’t get “cross-query shared state” capability either — for shared state, place it in module scope outside the handler closure.

Multi-tool Example


Stdio Server

Communicates with MCP servers via a child process’s stdin/stdout. The @modelcontextprotocol/server-* packages on NPM are all stdio implementations.

SSE / HTTP Server

For remote services requiring OAuth, see OAuth Authentication.

Tool Naming and Allowlists

The CLI uniformly prefixes MCP tools when exposing them to the model:
For example, server name my_tools with tool name greet gives the model the tool name mcp__my_tools__greet.

tools: Restrict Which Tools the Model Can See

Use tools when you want the model to only see a subset of tools. The CLI adds every built-in tool not in the list to the disallow set — effectively a visibility allowlist:
⚠️ Omitting tools means everything is exposed: all built-in tools plus every tool from connected MCP servers reach the model. For production, list them explicitly to tighten scope.

allowedTools: Pre-approval (Not a Visibility Allowlist)

allowedTools adds listed tools to the “always-allow” rule set — calls skip the permission prompt, but unlisted tools are not hidden. Use it to whitelist low-risk MCP tools for unattended use:
Omitting allowedTools just means no pre-approval rules — the model still sees and can call every tool, write operations simply route through the regular permissionMode approval flow. See Permissions docs for full semantics.

allowedMcpServerNames: Process-Server Allowlist

Only filters process-based (stdio/sse/http) servers; does not affect in-process servers. Combined with strictMcpConfig: true, it can prevent the CLI from loading additional local configurations:
⚠️ Omitting allowedMcpServerNames means all process servers connect; to tighten, list them explicitly. In-process servers are never filtered by this field.

Runtime Management (Query API)

The Query object returned by query() exposes several MCP-related methods. All methods communicate with the CLI via the control channel and are asynchronous and idempotent.
⚠️ Caching Principle: MCP server config/auth state changes rebuild the tools list, which breaks the prompt prefix cache mid-session. The SDK provides methods for “querying status + completing auth before the first message”; the server set itself should be configured once at startup via options.mcpServers, restarting query() when necessary.

Querying Status

💡 The MCP handshake occurs after the CLI completes initialize but before the first user message. Query status only after initializationResult() has returned to get real results — handshake IO may take a few hundred milliseconds; consider using pollUntil to wait for connected before proceeding.

Subscribing to Status Changes

MCP status uses pull rather than push: call await q.mcpServerStatus(). Implement polling in your own code when needed.

Changing the Server Set? Use Process-level Configuration

To keep the prompt prefix cache stable, server set changes are completed once at startup:

Controlling Request Timeout

After timeout, the SDK automatically writes a control_cancel_request and rejects the current Promise.

OAuth Authentication

Remote MCP servers (HTTP/SSE) often require OAuth. The CLI has a complete built-in OAuth 2.0 + PKCE + Dynamic Client Registration (RFC 7591) implementation.
⚠️ Caching Principle: After OAuth completes, the CLI reconnects to the server and rediscovers tools, which inevitably breaks the prompt prefix cache mid-session. Therefore, only “actively-driven” auth mode is supported — complete all auth before the first streamInput so the tools list stabilizes before sending the first user message.
💡 This section only covers CLI-driven OAuth: The CLI performs metadata discovery, PKCE, token exchange, and token persistence. There is another server-driven auth path — where the server uses MCP elicitation/create to have the client redirect to a URL for authorization (typical example: GitHub MCP). The two paths are independent and won’t trigger simultaneously: with server-driven auth, mcpServerStatus() won’t show needs-auth, and mcpAuthenticate shouldn’t be called; instead, the host uses onElicitation to handle the request. See Elicitation: Server Requests User Input.
The host controls OAuth timing, completing it before sending the first user message:
redirectUri is optional, overriding the default OAuth callback target (Electron custom protocol, enterprise intranet callback addresses, etc.). The CLI stores tokens in the system Keychain by default (macOS / Linux Secret Service), falling back to ~/.qoder/mcp-oauth-tokens.json (0o600 permissions + cross-process locking).

Elicitation: Server Requests User Input

MCP elicitation/create is a server → client request used to have the client display an interaction to the user. The SDK exposes these requests to the host via Options.onElicitation.

Two Modes

URL mode completes asynchronously: after the server receives user authorization in its own callback, it sends notifications/elicitation/complete — the SDK projects this as an SDKElicitationCompleteMessage pushed into the Query message stream.

Callback Signature

signal will abort on q.close() / interrupt; long-running processes should check it.

Form Mode Example

URL Mode Example (with elicitation_complete)

💡 Do not await the browser redirect inside onElicitation. The URL mode design is: the callback immediately returns accept (= user has started the flow), and the CLI does not block the control channel; the real “completion” signal comes from the subsequent elicitation_complete message. If you await the entire OAuth redirect, you’ll trigger the control request timeout (controlRequestTimeoutMs).

Boundary with the OAuth Path

  • CLI-driven OAuth (mcpAuthenticate / mcpSubmitOAuthCallbackUrl): Token stored in qodercli Keychain; driven when mcpServerStatus() shows needs-auth; does NOT trigger onElicitation.
  • Server-driven elicit URL: Token stays internal to the server; mcpServerStatus() won’t show needs-auth; handled via onElicitation; completed via system/elicitation_complete.
The two paths are not mutually exclusive but don’t overlap: the same server typically uses only one. If unsure which path a server uses: check whether it sends elicitation/create to the client during handshake — if it does, it’s server-driven.

Hook Channel

Hosts can also attach hooks in settings.json to intercept elicitation, with behavior taking priority over onElicitation:
⚠️ qodercli 0.2.x only sends elicitation: {} (empty object, compatible with Spring AI Java MCP SDK) in the MCP capability declaration. The MCP SDK server-side interprets this as equivalent to { form: {} }, so currently only form mode actually arrives at the client from remote servers. The URL mode protocol layer is complete, but requires the CLI to explicitly declare elicitation.url for the server-side elicitInput({ mode: 'url' }) to pass validation — this will evolve with CLI version updates.

Options Reference

Methods on Query

For adding/removing/modifying the server set, use options.mcpServers (configured at startup) + restart query(); see Changing the Server Set? Use Process-level Configuration.

Type Reference

McpServerStatus status enum:

Best Practices

  1. Write descriptions for the AI: The tool() description determines when the AI selects it. Clearly state “what it does, when to use it, what it should NOT be used for.”
  2. Use .describe() on fields: Always add .describe(...) to Zod fields; the AI uses this information to construct call parameters.
  3. Use isError for failures, don’t throw exceptions: Let the AI see the result. Exceptions confuse the model and may trigger retries.
  4. Prefer read-only + readOnlyHint: Be cautious with write operations; pair with canUseTool or hooks for secondary confirmation.
  5. Keep server names short: They appear in tool prefixes; overly long names waste tokens.
  6. Place in-process shared state in module scope: Handlers are closures, but each query still reuses the same server instance.
  7. Complete OAuth before the first streamInput: Use mcpAuthenticate + mcpSubmitOAuthCallbackUrl. Completing auth mid-session inevitably breaks the prompt prefix cache.
  8. Pull MCP status with mcpServerStatus(): The push channel has been retired; poll as needed.
  9. Set a reasonable controlRequestTimeoutMs: Remote server handshakes may take seconds; the default 60s is usually sufficient, but set it explicitly in CI environments.
  10. Use strictMcpConfig for isolation: Prevent MCP servers declared in the user’s local settings.json / .mcp.json from interfering with your application.

Complete Example