Yolk SDK
MCP

MCP package

List MCP tools, call them, or expose Yolk-compatible tools through MCP.

Use @yolk-sdk/mcp when your app needs to connect an agent to Model Context Protocol servers.

For auth, local stdio, and server policy, see MCP auth, local servers, and server policy.

Install:

pnpm add @yolk-sdk/mcp@canary @yolk-sdk/agent@canary effect@4.2.0

Connect with the full MCP v2 client

Use the official client API for tools, resources, prompts, completions, MRTR, subscriptions, response caching, and OAuth protocol helpers:

import { Client, StreamableHTTPClientTransport } from '@yolk-sdk/mcp/client'

const client = new Client(
  { name: 'my-app', version: '1.0.0' },
  { versionNegotiation: { mode: 'auto' } }
)

await client.connect(new StreamableHTTPClientTransport(new URL('https://example.com/mcp')))

const tools = await client.listTools()
const resources = await client.listResources()
const prompts = await client.listPrompts()

mode: 'auto' prefers stateless MCP 2026-07-28 and falls back to initialize-based servers. Use { pin: '2026-07-28' } for modern-only behavior. The upstream Client default remains legacy for compatibility.

Import official wire schemas from @yolk-sdk/mcp/core. Import Node stdio transports from @yolk-sdk/mcp/client/node and @yolk-sdk/mcp/server/node.

List remote MCP tools for a Yolk agent

import { Effect } from 'effect'
import { FetchHttpClient } from 'effect/http'
import type { McpRemoteServerConfig } from '@yolk-sdk/mcp/client'
import { listRemoteMcpServerTools } from '@yolk-sdk/mcp/client'

const config = {
  name: 'docs',
  type: 'remote',
  url: 'https://example.com/mcp'
} satisfies McpRemoteServerConfig

const tools = await Effect.runPromise(
  listRemoteMcpServerTools(config).pipe(Effect.provide(FetchHttpClient.layer))
)

Each item contains:

  • serverName
  • original mcpToolName
  • Yolk ToolDef as def

Pass tools.map(tool => tool.def) into the agent loop.

Call a remote MCP tool

import { makeToolFileCapture } from '@yolk-sdk/agent/tools'
import { callRemoteMcpServerTool } from '@yolk-sdk/mcp/client'

const result = await Effect.runPromise(
  callRemoteMcpServerTool({
    config,
    mcpToolName: 'search',
    toolCallId: 'call_123',
    params: { query: 'Yolk SDK' },
    // Stores the call's blobs, images and audio (`store` is your FileStoreApi).
    fileCapture: makeToolFileCapture({ store })
  }).pipe(Effect.provide(FetchHttpClient.layer))
)

The result is a Yolk ToolResult, ready to feed back into the agent loop. Its structuredContent is { value, files }: value is the server's structuredContent (checked against the listed outputSchema), else the text of its text blocks and embedded text resources, parsed once when it is one JSON object or array; files are its blobs, images and audio as FileRef (or FileUnavailable). Inside a resolveTools registration the files are stored through the resolution's files; a call made anywhere else (a route, a resume) passes fileCapture, or every file is FileUnavailable (no file store) and the blob is lost: MCP blobs cannot be fetched again. Registrations built from listed tools set decodeOutput: mcpToolOutputDecoder (Add MCP tools).

Confirm tool calls with form elicitation

Some servers confirm destructive tools with MCP form elicitation over multi round-trip requests (MRTR, protocol 2026-07-28): the first tools/call answers an InputRequiredResult (a form plus an opaque requestState), and the client retries the same call with the user's decision. Yolk models this for durable hosts: nothing blocks waiting for a person.

Opt in with elicitation: { form: true }. The listing and the resumable call functions then declare elicitation.form in the per-request _meta client capabilities of a modern connection (never in a legacy initialize). callRemoteMcpServerToolResumable answers a typed outcome:

An integration fragment: collectDecision stands for the host's own flow (persist the pause, show the form to a person, await their answer, possibly in another process). Never auto-accept a confirmation; when no person decides, answer decline or cancel.

import { makeToolFileCapture } from '@yolk-sdk/agent/tools'
import {
  callRemoteMcpServerToolResumable,
  resumeRemoteMcpServerToolCall,
  type McpClientOptions,
  type McpElicitationResponse,
  type McpFormElicitation
} from '@yolk-sdk/mcp/client'

// Host-owned: renders the form, waits for a person, and returns their decision.
declare const collectDecision: (form: McpFormElicitation) => Promise<McpElicitationResponse>

const options: McpClientOptions = { elicitation: { form: true } }

// The resume runs outside `resolveTools` (a HITL route, another process): pass a capture, or the
// resumed result's blobs are `FileUnavailable` and lost (`store` is your FileStoreApi).
const call = {
  config,
  mcpToolName: 'delete-invoice',
  toolCallId: 'call_123',
  params,
  options,
  fileCapture: makeToolFileCapture({ store })
}

const outcome = await Effect.runPromise(
  callRemoteMcpServerToolResumable(call).pipe(Effect.provide(FetchHttpClient.layer))
)

if (outcome._tag === 'InputRequired') {
  // Persist `outcome.inputRequired` first: the decision may take hours and another process.
  const pending = outcome.inputRequired
  const entries: Array<[string, McpElicitationResponse]> = []

  for (const form of pending.elicitations) {
    // One decision per form, keyed by `form.key`, from a person.
    entries.push([form.key, await collectDecision(form)])
  }

  // `Object.fromEntries` keeps any server key as an own property (even `__proto__`).
  const responses = Object.fromEntries(entries)

  const resumed = await Effect.runPromise(
    resumeRemoteMcpServerToolCall({ ...call, inputRequired: pending, responses }).pipe(
      Effect.provide(FetchHttpClient.layer)
    )
  )
}

McpInputRequired is a Schema class: encode it with Schema.encodeUnknownEffect to persist it and decode it in another process. Each McpFormElicitation carries the server's key, message, and requestedSchema (flat primitive properties, kept as received). The pause is bound to its call (mcpToolName, argumentsDigest) and carries the listed tool definition. Answer every elicitation with accept (with content), decline, or cancel; decisions are checked against each form (type (integer vs number), required, const, enum, titled oneOf, minLength/maxLength, format (email, uri, date, date-time), minimum/maximum, items.enum, titled items.anyOf, minItems/maxItems) before sending, and the server validates them again. The resume is re-sent as a new request on a new connection with the same tool call, the exact requestState, and the decisions as inputResponses. It lists nothing: the pause's tool definition (name, inputSchema, outputSchema) drives header mirroring and the structured-output check, and an invalid one fails malformed before sending. With that definition the official client does not re-list and retry after a HEADER_MISMATCH (-32020), so a server that changed the tool's x-mcp-header declarations since the pause answers McpError (cause: 'protocol'). The server may pause again.

Failures are typed. McpInputRequiredError covers a malformed or too_large pause. The default bound is 256 KiB of JSON and 16 requests; set elicitation.maxInputRequiredBytes to a positive integer (checked before connecting). It applies separately to the server-provided pause (checked after the body is buffered, without the tool definition) and to the listed tool definition (checked before the call, so an oversized definition fails with nothing sent and never strands a pause). It also covers an unsupported_request (URL mode, sampling, roots, or any input without the opt-in), invalid_responses and mismatched_resume (another tool or other arguments; both checked before sending), and unsupported_era (resuming on a legacy connection). The pause is decoded from the raw input_required response as the server sent it: the response the official client resolves the call with (matched by its own Number(id) coercion; an id not identical to the call's fails malformed), captured at the transport before the client normalises it. A non-string requestState or non-object inputRequests fails malformed instead of passing as a valid or load-shedding pause; responses with other ids are ignored. Formats are checked by syntax: RFC 3339 dates (a leap second only at 23:59:60 UTC), an absolute RFC 3986 URI (IPv6 literals per its grammar; not WHATWG URL parsing), and a pragmatic mailbox (a dot-atom local part, @, a hostname of at least two labels). MCP -32021 becomes McpClientCapabilityRequiredError with requiredCapabilities. A server that reports a missing capability as a tool error (for example Afloat's CLIENT_CAPABILITY_REQUIRED) answers a Complete outcome with isError: true.

Legacy (pre-2026-07-28) elicitation is a server-initiated request that must be answered while the call is open, so it is not supported: an opted-in host never declares elicitation on a legacy connection. callRemoteMcpServerTool keeps its behavior and never declares it.

In an agent session, a registration stores the pause and returns an input-required result, and a person answers through the input review interaction: see Finish calls that ask for input.

Use local stdio MCP

Use @yolk-sdk/mcp/client/node only in Node hosts:

See MCP auth, local servers, and server policy for a runnable Node example, explicit environment rules, and the required allowLocalServers opt-in.

Worker/browser code should stay on @yolk-sdk/mcp/client.

Build a full MCP v2 server

Use McpServer and createMcpHandler for tools, resources, prompts, completions, MRTR, and subscriptions:

import { McpServer, createMcpHandler } from '@yolk-sdk/mcp/server'

const handler = createMcpHandler(() => {
  const server = new McpServer({ name: 'my-server', version: '1.0.0' })
  // Register tools, resources, and prompts here.
  return server
})

export default { fetch: handler.fetch }

createMcpHandler serves stateless MCP 2026-07-28 and legacy initialize-based HTTP clients. Put deployment authentication plus Origin and Host validation in front of handler.fetch.

Expose Yolk tools through MCP

Use makeMcpToolServer from @yolk-sdk/mcp/server to expose a tool-only Yolk adapter. Its HTTP entrypoint accepts both modern and legacy requests. Use the official McpServer surface when you need other core capabilities.

A request that carries MCP-Protocol-Version with a body over maxRequestBodySize (default 4 MiB) is answered 413; a host that accepts larger bodies passes its own cap to makeMcpToolServer. The header-less JSON path reads the body unbounded, so the host caps it.

To ask the user before a tool runs, give the tool an approval policy and the server approvals (a signing key of at least 32 bytes and the request's authenticated principal). The first call answers an MCP form elicitation over multi round-trip requests (2026-07-28), one required approve/deny choice (never an empty form, which some clients accept without showing it), with a signed, expiring requestState; only a retry that approves it for the same principal, tool, arguments and prompt runs the tool, with an approvalId to run it at most once. The prompt is built again on the retry, so build it deterministically: an accept of a prompt that changed since the user saw it runs nothing. To ask a form instead (yes/no, one choice, or a multi-select of titled options), build the tool with makeMcpServerElicitedTool and mcpServerForm: execute gets the answer decoded with the form's schema, and an answer that does not fit asks again. Clients that do not declare form elicitation get an error result, and 2025-era requests are not offered approval or elicited tools. See the package README.

Forward a remote tool's forms

A tool that proxies a remote MCP tool can pass the remote server's form elicitation on to this server's own client. Give it forward: true (an McpServerForwardingTool, optionally with its own approval) and the server approvals. execute(call, round) runs one round and answers the remote McpToolCallOutcome:

Fragment: remoteConfig, def, and the HttpClient layer are host-owned.

import { Effect } from 'effect'
import {
  callRemoteMcpServerToolResumable,
  resumeRemoteMcpServerToolCall
} from '@yolk-sdk/mcp/client'
import { McpForwardRound, McpServerError, type McpServerTool } from '@yolk-sdk/mcp/server'

const proxyDelete: McpServerTool = {
  def,
  forward: true,
  execute: (call, round) => {
    const remote = {
      config: remoteConfig,
      mcpToolName: 'delete',
      toolCallId: call.id,
      params: call.params
    }

    return McpForwardRound.$match(round, {
      // Opt into elicitation only when this server can forward a pause.
      Initial: ({ clientElicitation }) =>
        callRemoteMcpServerToolResumable({
          ...remote,
          options: clientElicitation ? { elicitation: { form: true } } : {}
        }),
      // Key once-only resumption on `roundId` (host-owned).
      Resume: ({ inputRequired, responses }) =>
        resumeRemoteMcpServerToolCall({
          ...remote,
          inputRequired,
          responses,
          options: { elicitation: { form: true } }
        })
    }).pipe(
      Effect.provide(httpClientLayer),
      Effect.mapError(error => new McpServerError({ message: error.message, cause: 'tool_error' }))
    )
  }
}
  • McpForwardRound.Initial({ clientElicitation, approvalId }) calls the remote tool. clientElicitation is true only on a 2026-07-28 request that declares form elicitation, with approvals configured: without it, a remote server that needs input refuses to run instead of pausing a call nobody can answer.
  • A remote pause is answered as this server's own InputRequiredResult (the remote forms under their keys) with a requestState signed (not encrypted) by the approvals key under its own binding. It holds the tool, the arguments digest, the pause's roundId and expiry (ttlSeconds after it was forwarded), the approval id, and the remote pause, at most mcpForwardMaxStateBytes (64 KiB) of JSON. The client can read the remote forms and requestState.
  • McpForwardRound.Resume({ roundId, inputRequired, responses, approvalId }) runs only for a round whose verified state matches the call and answers every forwarded form (checked against the forms); other rounds are asked again in the same round (same roundId and expiry). A state that does not verify, or expired, answers forwardStaleMessage and calls nothing (with approval, the approval is asked again). The server keeps no state, so a replayed answered round arrives again with the same roundId: key once-only resumption on it.
  • The host may answer a duplicate key (a retried accept on approvalId, a retried Resume on roundId) with the outcome it stored. A remote pause's roundId is derived from the approval or round it came from and the pause itself, so a replayed pause is forwarded again under the same roundId and still resumes once. A replay is accepted only while its origin (the approval or round state) is still valid, and the replayed pause then gets a fresh expiry. A first round without approval has no key, and its pause gets a random roundId.
  • With approval, the tool is offered like an approval tool: the approval round runs first and every forward round carries its approvalId. Without it, the tool is listed everywhere; 2025-era requests and the header-less JSON path run only Initial with clientElicitation: false.
  • A remote pause that cannot be forwarded answers an error result: forwardUnsupportedMessage (the client cannot answer forms), forwardEmptyPauseMessage (a pause without a form), forwardOversizedMessage, or forwardMalformedMessage.

No tool call outlives handleHttpRequest's Effect, so you can provide its requirements from a scoped request layer. When an answer other than subscriptions/listen is an SSE stream (always for 2025-era requests), it is read to its end first and returned with the same status, headers and events (a read failure answers 500 with -32603), and a tool still running when the Effect ends is interrupted and awaited. A subscriptions/listen request is answered with its acknowledgement and a complete result: this server has no change notifications to stream. For requests that carry MCP-Protocol-Version, a client cancellation (on Streamable HTTP, closing the response stream) interrupts the tool's Effect.

Conformance cases

@yolk-sdk/mcp/conformance (experimental) holds nine read-only conformance cases that check the wire claims the remote client relies on, against any MCP server you point them at, plus the opt-in mcpElicitationDeclarationCase for hosts that declare form elicitation and the opt-in mcpServerPingCase for legacy servers that ping their clients. See MCP conformance.

Security defaults

Remote MCP requires HTTPS by default. Localhost HTTP is an explicit dev policy. Local stdio receives explicit env only and does not inherit host process env by default.

On this page