Cogitator
Integrations

Model Context Protocol (MCP)

Full MCP support (2026-07-28 and 2025-11-25) -- connect to external MCP servers to use their tools, or expose Cogitator tools and agents as an MCP server.

Overview

The @cogitator-ai/mcp package provides bidirectional MCP integration:

  • MCPClient -- connect to any MCP server (filesystem, database, GitHub, etc.) and use its tools inside Cogitator agents.
  • MCPServer -- expose your Cogitator tools, resources, and prompts as an MCP server for Claude Desktop, other AI assistants, or any MCP client.
  • Tool Adapter -- convert between Cogitator and MCP tool formats, including Zod-to-JSON Schema conversion.

Client and server speak MCP 2026-07-28 (stateless requests, server/discover, multi round-trip requests, tasks, subscriptions/listen, OAuth with Client ID Metadata Documents) and 2025-11-25 with peers that have not moved yet.

pnpm add @cogitator-ai/mcp @cogitator-ai/core

MCPClient

Connecting to an MCP Server

Use MCPClient.connect() to establish a connection. The client discovers server capabilities automatically and provides access to tools, resources, and prompts.

import { MCPClient } from '@cogitator-ai/mcp';

const client = await MCPClient.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-filesystem', '/home/user/documents'],
  timeout: 10000,
});

console.log(client.getCapabilities());

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

await client.close();

Using MCP Tools with Agents

The tools returned by getTools() are standard Cogitator Tool instances -- pass them directly to an agent:

import { Cogitator, Agent } from '@cogitator-ai/core';
import { MCPClient } from '@cogitator-ai/mcp';

const fsClient = await MCPClient.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-filesystem', '/workspace'],
});

const dbClient = await MCPClient.connect({
  transport: 'http',
  url: 'http://localhost:3001/mcp',
});

const fsTools = await fsClient.getTools();
const dbTools = await dbClient.getTools();

const agent = new Agent({
  name: 'file-manager',
  model: 'openai/gpt-6.1-sol',
  instructions: 'Help users manage files and query databases.',
  tools: [...fsTools, ...dbTools],
});

const cog = new Cogitator({/* ... */});
const result = await cog.run(agent, {
  input: 'List all .ts files in /workspace/src and count them',
});

await fsClient.close();
await dbClient.close();

connectMCPServer Helper

For the common pattern of connect-get-tools-cleanup, use the shorthand:

import { connectMCPServer } from '@cogitator-ai/mcp';

const { tools, cleanup } = await connectMCPServer({
  transport: 'stdio',
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-github'],
  env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN! },
});

const agent = new Agent({
  name: 'github-bot',
  model: 'openai/gpt-6.1-sol',
  instructions: 'Answer questions about GitHub repositories.',
  tools,
});

await cleanup();

It also returns the connected client. For stdio servers, env is merged over the current process environment.

MCPClientConfig

OptionTypeDescription
transport'stdio' | 'http' | 'sse'Transport protocol ('sse' is an alias of 'http')
commandstringCommand for stdio transport
argsstring[]Command arguments for stdio
envRecord<string, string>Environment variables for stdio
cwdstringWorking directory for the stdio process
urlstringServer URL for HTTP/SSE transport
headersRecord<string, string>Extra HTTP headers (e.g. Authorization)
timeoutnumberConnection timeout in ms (default: none)
clientNamestringClient identification name
clientVersionstringClient version string
retryMCPRetryConfigRetry settings for failed operations
autoReconnectbooleanAuto-reconnect on connection loss (default: true)
onReconnecting, onReconnected, onReconnectFailedcallbacksReconnection lifecycle hooks
protocol'auto' | 'legacy' | { pin }Protocol revision (default: 'auto')
elicitationfalse | handlerAnswers input requests no run can answer
tasksboolean | { store }Take MCP tasks (default: true)
authMCPOAuthConfig | providerOAuth 2.1 for a remote server
maxInputRoundsnumberRounds of input requests per call (default: 10)

The http transport speaks MCP Streamable HTTP (sse is an alias of it, as the server's sse serves it). A server that only offers the older HTTP+SSE protocol, which opens its event stream with a GET and takes messages in POSTs, needs transport: 'legacy-sse', which experimental_mcpConnector() uses for type: "sse" of a .mcp.json, as Claude Code does. Besides getTools(), the client has listToolDefinitions() (raw MCP definitions), isConnected(), reconnect() and close().

Protocol Versions

MCP 2026-07-28 has no initialize handshake: each request carries its protocol version and the client's capabilities in _meta, and the server describes itself through server/discover. With protocol: 'auto' (the default) the client asks server/discover first and speaks 2026-07-28 to a server that answers, 2025-11-25 to any other. On stdio the probe runs in a short-lived copy of the server process, so a stdio server starts twice on the first connect. A reconnect keeps the revision and asks nothing. protocol: 'legacy' keeps the old behavior, { pin: '2026-07-28' } fails against older servers.

const client = await MCPClient.connect({ transport: 'http', url });
client.era; // 'modern' | 'legacy'
client.discover(); // { protocolVersion, supportedVersions, capabilities, instructions, serverInfo }

Input Requests

A 2026-07-28 server asks the person at the client by answering a call with input requests, and the client calls again with the answers and the server's requestState, byte for byte. A tool from getTools() asks through its run: the run pauses with an interrupt (reason: 'mcp_elicitation', the server's form as responseSchema), and cogitator.resume() with the answer runs the tool again, which sends the answer to the round the server asked in (kept by tool call id in rounds.store, for rounds.ttlMs), so the server goes on with the same call instead of starting another. cancelPause() declines. Outside a run the elicitation handler answers, and without one the client tells the server nobody can answer. The handler also answers the elicitation/create requests of 2025-11-25 servers.

Tasks and Subscriptions

A server may answer a long call with a task. The client polls it at the interval the server suggests, answers its questions, reports its status message through the tool's update, and cancels it when the call's signal aborts. A task outlives a lost connection, and a call that runs again after a pause polls the task it started (tasks are kept by tool call id, tasks: { store } keeps them elsewhere).

client.subscribe(filter, handlers) hears of tool, prompt and resource changes: a subscriptions/listen stream on 2026-07-28, list changes and per-resource subscriptions on earlier revisions. subscription.filter is what the server agreed to report.

OAuth

const client = await MCPClient.connect({
  transport: 'http',
  url: 'https://mcp.example.com/mcp',
  auth: {
    redirectUrl: 'http://127.0.0.1:8976/callback',
    clientMetadataUrl: 'https://my-app.example.com/oauth/client.json',
    authorize: async (url) => openBrowserAndWaitForCallback(url),
  },
});

On a 401 the client discovers the authorization server from the server's Protected Resource Metadata, registers, sends the person to authorize (PKCE, the server as resource), checks the iss of the answer and connects with the token. It registers with a pre-registered clientId, else with its Client ID Metadata Document (an HTTPS JSON document you host, its URL the client_id) when the authorization server supports those, else by Dynamic Client Registration as a native app for a loopback redirect. Registrations and tokens are kept per authorization server in store, under the MCP server's URL, so a shared store never sends one server's token to another. A token or registration the authorization server rejects is forgotten for every authorization server.

Retry and Reconnection

The client has built-in retry with exponential backoff for all operations. On connection loss, it automatically reconnects:

const client = await MCPClient.connect({
  transport: 'http',
  url: 'http://mcp-server:3000/mcp',
  retry: {
    maxRetries: 5,
    initialDelay: 1000,
    maxDelay: 30000,
    backoffMultiplier: 2,
    retryOnConnectionLoss: true,
  },
  onReconnecting: (attempt) => console.log(`Reconnecting (attempt ${attempt})...`),
  onReconnected: () => console.log('Reconnected'),
  onReconnectFailed: (err) => console.error('Reconnection failed:', err),
});

Only transient failures are retried (connection loss, request timeouts, network errors). Protocol errors returned by the server, tool failures and aborted calls fail immediately, and concurrent calls that lose the connection share a single reconnect.

Tool calls are only retried when sending them twice is harmless. After a timeout or a lost connection the server may still be running the call, or may have finished it, so callTool throws MCPToolInterruptedError (reason: 'timeout' | 'connection-lost') instead of deploying twice or sending a second email. A resumed call whose task the server no longer knows (it expired) throws the same error with reason: 'task-lost' rather than calling the tool again. Tools from getTools() / wrapMCPTools() are retried like reads when the server marks them readOnlyHint or idempotentHint in their annotations. Pass { idempotent: true } to callTool to retry a call yourself. A connection an earlier call lost is restored before the next call is sent.

Tool Results and Errors

callTool returns structuredContent when the server provides it (any JSON value since 2026-07-28), otherwise the unwrapped content (text blocks are JSON-parsed when possible, a single block is returned on its own, an empty result is null). Content with images, audio or binary resources comes back as a toolContent() result, so the model sees a screenshot as an image and audio stays out of the context. Text resources in such a result become resource parts with their URI, media type and text. With structuredDetails: true the structuredContent that such a result leaves out comes back too: the call returns a toolOutput() result, the value as its content for the model and { structuredContent } (ToolStructuredDetails) as its details. Tools from getTools() / wrapMCPTools() set it, so a run keeps the structured result in the call's details (onToolResult, the metadata of the tool_result entry) and a host such as Studio gives it to the tool's app, while the model reads the same media as before. A tool result with isError: true throws MCPToolError, so MCP failures show up as ordinary tool errors inside agent runs. Pass an AbortSignal to cancel a call, and tools created by getTools() forward the run's signal automatically.

import { MCPToolError } from '@cogitator-ai/mcp';

try {
  await client.callTool('write_file', { path: '/etc/passwd', content: '' }, { timeout: 5_000 });
} catch (error) {
  if (error instanceof MCPToolError) {
    console.error(`${error.toolName} failed: ${error.message}`);
  }
}

Approval for Destructive Tools

Tools from getTools() / wrapMCPTools() keep the server's title, its hints as annotations and its outputSchema as a zod schema of the result. A tool the server marks destructive (destructiveHint: true without readOnlyHint: true) gets requiresApproval: true, so an agent run pauses for approval before it runs, and cogitator.invokeTool() asks onApproval. A tool without the hint is not taken as destructive, although MCP's own default for a missing destructiveHint is true: that would ask approval for every tool of most servers. Hints come from the server and are only as trustworthy as it is, so they only ever add approval.

import { isDestructiveMCPTool } from '@cogitator-ai/mcp';

const tools = await client.getTools(); // destructive tools need approval
const everyCall = await client.getTools({ requiresApproval: true });
const noneOfThem = await client.getTools({ requiresApproval: false });
const custom = await client.getTools({
  requiresApproval: (tool) => isDestructiveMCPTool(tool) || tool.name.startsWith('delete_'),
});

Resources and Prompts

Beyond tools, MCP servers can expose resources (data sources) and prompts (reusable prompt templates):

const resources = await client.listResources();

const content = await client.readResource('file:///workspace/config.json');
console.log(content.text);

const prompts = await client.listPrompts();

const messages = await client.getPrompt('code-review', {
  language: 'typescript',
  style: 'thorough',
});

readResource returns the first content block; readResourceContents returns all of them.

MCPServer

Exposing Cogitator Tools

Create an MCP server to make your Cogitator tools available to any MCP client:

import { MCPServer } from '@cogitator-ai/mcp';
import { tool } from '@cogitator-ai/core';
import { z } from 'zod';

const calculator = tool({
  name: 'add',
  description: 'Add two numbers',
  parameters: z.object({ a: z.number(), b: z.number() }),
  execute: async ({ a, b }) => ({ sum: a + b }),
});

const server = new MCPServer({
  name: 'my-tools',
  version: '1.0.0',
  transport: 'stdio',
});

server.registerTools([calculator]);
await server.start();

Tool calls run the way an agent run executes them, through a ToolInvoker (cogitator.invokeTool()): the arguments are validated, a tool with requiresApproval (or one the guardrails flag) is asked from the person at the client through MCP elicitation, the guardrails apply, sandboxed tools run in the sandbox, tool.timeout holds and the Cogitator's wrapToolCall middleware applies. Pass your Cogitator as toolInvoker so its sandbox and guardrails are the ones used, otherwise the server uses a Cogitator of its own without configuration. For 2026-07-28 clients the approval ends the round: the client gets the approval form with a signed requestState (HMAC under requestStateKey, bound to the caller, the tool and its arguments, valid for twice elicitationTimeoutMs), and the call runs once it comes back approved. A call that needs approval when nobody can be asked (a client without elicitation, or a 2025-11-25 client over HTTP without sessions: true) does not run: it comes back as an isError result that says so, unless the invoker's guardrails.onToolApproval decides it.

const server = new MCPServer({
  name: 'ops',
  version: '1.0.0',
  transport: 'stdio',
  toolInvoker: cog,
});

@cogitator-ai/mcp/server exports MCPServer, serveMCPTools and InMemoryMCPTaskStore without the MCP client. A server that takes its tools from @cogitator-ai/core/tool starts without the runtime: it answers initialize and lists its tools right away, and loads @cogitator-ai/core with the first tool call that runs through a Cogitator of its own (never when toolInvoker is set).

import { MCPServer } from '@cogitator-ai/mcp/server';
import { tool } from '@cogitator-ai/core/tool';

serveMCPTools(tools, config) does the same in one call and returns the started server. Tools, resources and prompts can be added one by one (registerTool, registerResource, registerPrompt) or in batches (registerTools, registerResources, registerPrompts), removed with the matching unregister* methods and listed with getRegisteredTools() / getRegisteredResources() / getRegisteredPrompts().

A tool's title, annotations and outputSchema reach the clients with it. The result of a tool with an output schema is sent as structuredContent, with its JSON as text for clients that read only content, and a result the schema rejects comes back as an isError result that says why. The output schema may have any root (an array, a record, a union): 2025-11-25 clients get such a result wrapped as { result }. Imported tools carry the server's output schema to the model: Gemini takes it as responseJsonSchema, other providers read it at the end of the description with llm.toolOutputSchemas: 'description'.

const getRepo = tool({
  name: 'get_repo',
  title: 'Repository details',
  description: 'Get the details of a repository',
  parameters: z.object({ repo: z.string() }),
  outputSchema: z.object({ repo: z.string(), stars: z.number() }),
  annotations: { readOnlyHint: true, openWorldHint: false },
  execute: async ({ repo }) => ({ repo, stars: 42 }),
});

A served tool that returns toolContent() answers with MCP content blocks instead of JSON text: text parts as text, images as image blocks, audio files as audio blocks, other files as embedded resources, json parts as their JSON text, and resource parts with text or data as embedded resources under their own URI (a resource part with neither becomes the line that names it).

HTTP Transport

For remote access, use the HTTP transport:

const server = new MCPServer({
  name: 'remote-tools',
  version: '1.0.0',
  transport: 'http',
  port: 3000,
  host: 'localhost',
  logging: true,
});

server.registerTools([calculator, webSearch, fileReader]);
await server.start();

Clients connect to http://localhost:3000/mcp (port defaults to 3000, host to localhost; other paths answer 404). Use port: 0 to bind a random free port and read it back with server.getPort(). maxBodySize (default 10 MB), corsOrigin (default '*') and auth (see below) tune the HTTP endpoint; start() rejects if the port cannot be bound and stop() closes open connections.

Tool arguments are validated against the tool's full Zod schema before execute runs; invalid arguments and thrown errors come back to the client as isError tool results, while errors thrown by resource read and prompt get handlers are returned as JSON-RPC errors. With logging: true, diagnostics go to stderr so the stdio transport's stdout stays reserved for JSON-RPC.

The server speaks 2026-07-28 and 2025-11-25 (legacyClients: false refuses the older revision). CORS preflights may send the MCP headers, Mcp-Param-* included, and allowedOrigins refuses other browser origins with 403. Without it a server on a loopback host takes only loopback origins (and requests without Origin), against DNS rebinding. A call still running after tasks.promoteAfterMs (default 2 s) becomes an MCP task for clients that take tasks, its approvals and questions asked in the task, and tasks/cancel stops its run. Tasks belong to the caller that started them: its userId, else a digest of its Authorization or Cookie header (auth that gives neither is answered 401). A task question nobody answers within elicitationTimeoutMs counts as dismissed, and a task still running at tasks.ttlMs is stopped. tasks: false turns them off.

Authentication and Per-User Tools

Over HTTP the server is open to anyone who can reach it. Pass auth to establish the caller of every request, usually from its bearer token; it receives the raw http.IncomingMessage and returns an MCPCaller ({ userId?, scopes?, metadata? }). Requests it returns undefined for (or throws on) are answered 401 with WWW-Authenticate: Bearer. The caller's userId reaches tools as context.userId, and resource read and prompt get handlers receive the caller as their second argument:

import { MCPServer, type MCPAuthFunction } from '@cogitator-ai/mcp';

const auth: MCPAuthFunction = async (request) => {
  const token = request.headers.authorization?.replace(/^Bearer /, '');
  const session = token ? await sessions.find(token) : undefined;
  return session ? { userId: session.userId, scopes: session.scopes } : undefined;
};

const listMyOrders = tool({
  name: 'list_my_orders',
  description: "List the calling customer's orders",
  parameters: z.object({}),
  execute: async (_args, context) => orders.forUser(context.userId!),
});

const server = new MCPServer({ name: 'shop', version: '1.0.0', transport: 'http', auth });
server.registerTool(listMyOrders);

An agent then acts for one user by connecting with that user's token:

const client = await MCPClient.connect({
  transport: 'http',
  url: 'https://shop.example.com/mcp',
  headers: { Authorization: `Bearer ${userToken}` },
});
const agentForUser = support.clone({ id: support.id, tools: await client.getTools() });
await cog.run(agentForUser, { input, userId, threadId });

The full flow, including thread isolation between users, is in examples/mcp/03-per-user-mcp.ts.

Registering Resources

Expose data sources as MCP resources:

server.registerResource({
  uri: 'config://app/settings',
  name: 'App Settings',
  description: 'Current application configuration',
  mimeType: 'application/json',
  read: async () => ({
    uri: 'config://app/settings',
    text: JSON.stringify(await loadAppSettings()),
  }),
});

A URI with {placeholders} is registered as a resource template; the matched values arrive in params. read may return one content or an array, and uri defaults to the URI that was read:

server.registerResource({
  uri: 'db://users/{userId}',
  name: 'User Profile',
  description: 'Fetch a user profile by ID',
  read: async (params) => ({
    uri: `db://users/${params.userId}`,
    text: JSON.stringify(await db.getUser(params.userId)),
  }),
});

Registering Prompts

Expose reusable prompt templates:

server.registerPrompt({
  name: 'code-review',
  title: 'Code Review',
  description: 'Generate a code review for the given language',
  arguments: [
    { name: 'language', description: 'Programming language', required: true },
    { name: 'style', description: 'Review depth: quick or thorough' },
  ],
  get: async (args) => ({
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Review this ${args.language} code. Style: ${args.style ?? 'thorough'}.`,
        },
      },
    ],
  }),
});

Serving Agents

serveAgents turns Cogitator agents into an MCP server in one call. Each agent becomes a tool that takes a task (and optionally the threadId of an earlier answer, to continue that conversation — needs memory on the Cogitator) and answers with the agent's reply:

import { serveAgents } from '@cogitator-ai/mcp';

await serveAgents(cog, [researcher, writer]); // stdio — for Claude Desktop, Cursor, Claude Code
await serveAgents(cog, support, { transport: 'http', port: 3333, auth }); // remote, per-user

In the client's MCP config:

{ "mcpServers": { "cogitator": { "command": "npx", "args": ["tsx", "my-agents.ts"] } } }

The tool answers { status: 'completed', output, threadId }. Each tool is named after its agent, with characters other than letters, digits, _ and - replaced (toolNames: { [agent.name]: 'tool_name' } renames them), and described by the agent's description — or by the first sentence of its instructions when it has none. serveAgents takes every MCPServer option (defaults: name cogitator-agents, transport: 'stdio', sessions: true) and returns the started server. With auth, runs carry the caller's userId, so threads and memory stay per user (Multiple Users), and the client's cancellation aborts the run.

Approvals. When an agent's tool needs approval, the server asks the person at the client through MCP elicitation and the run goes on with their answer. For 2026-07-28 clients the run pauses, the round ends with every approval and question it waits on and a signed state that names its thread, and the next round resumes it with the decisions and answers, so nothing waits in the server between rounds. Clients without elicitation get a paused answer ({ status: 'paused', threadId, pendingApprovals, next }) and continue with the <agent>_resume tool (the agent's tool name plus _resume, registered for every agent, since permission rules of the runtime can make any call ask), passing { threadId, approved, reason? } once the user decided. The approval message says why the call asks. With allowRemember: true in the server options, elicitation offers an always choice and <agent>_resume takes remember, which saves the request's suggested rule. It is off by default, so the client model cannot grant itself standing permissions. Imported MCP tools carry their server and name (tool.mcp, the server from the server option of wrapMCPTools(), else the name the server reports), so mcp__<server>__<tool> rules match them. Elicitation needs a connection the client can reply on: stdio, or HTTP with sessions: true, which serveAgents turns on.

agentTools(cog, agents, toolNames?) returns the same tools to register on an MCPServer you configure yourself. Both accept anything with Cogitator's run and resume (AgentHost).

Instructions and the request

instructions in the server's config is what it tells every client about itself when it connects. Clients hand it to their model next to the tools, so it is the place for what holds across tools: the order to call them in, what to do after a call.

A tool also learns what came with the call besides its arguments: context.request.meta is the _meta of the request without the protocol's own keys, where clients put what identifies the call (Codex its thread and turn, Claude Code the id of the tool use), and context.request.client is the client's name and version. A tool that takes keys outside its schema (z.looseObject) gets them as sent.

const whoami = tool({
  name: 'whoami',
  description: 'Say which client and thread is calling',
  parameters: z.object({}),
  execute: async (_args, context: MCPToolContext) => {
    const client = context.request?.client?.name ?? 'an unnamed client';
    const thread = context.request?.meta?.threadId;
    return typeof thread === 'string' ? `${client}, thread ${thread}` : client;
  },
});

const server = new MCPServer({
  name: 'my-tools',
  version: '1.0.0',
  transport: 'stdio',
  instructions: 'Call whoami first. Its answer names the thread the other tools act for.',
});

Sessions

2026-07-28 clients have no sessions: the server asks them with the answer of a round. For 2025-11-25 clients MCPServer over HTTP serves each request on its own by default, and sessions: true keeps a session per client (mcp-session-id), which requests from the server to such a client, like elicitation, need. A session belongs to the caller that started it: a request with another caller's credentials gets 403.

elicit keeps a 2026-07-28 call waiting in the server process between rounds, so every round of it has to reach the same process. A round for a question that expired or was answered already gets an error result, the tool does not run again. context.input asks without waiting: input.ask(requests, state) ends the round, and the tool runs again with input.responses and its state, on any process with the same requestStateKey.

Your own tools reach the elicitation channel through their context. elicit resolves to { action: 'accept', content }, { action: 'decline' | 'cancel' }, or undefined when the client cannot answer:

import type { MCPToolContext } from '@cogitator-ai/mcp';

const deleteOrder = tool({
  name: 'delete_order',
  description: 'Delete an order after the user confirms',
  parameters: z.object({ orderId: z.string() }),
  execute: async ({ orderId }, context) => {
    const reply = await (context as MCPToolContext).elicit?.({
      message: `Delete order ${orderId}?`,
      schema: {
        type: 'object',
        properties: { confirm: { type: 'boolean', title: 'Confirm' } },
        required: ['confirm'],
      },
    });
    if (reply?.action !== 'accept' || reply.content.confirm !== true) return { deleted: false };
    await orders.delete(orderId);
    return { deleted: true };
  },
});

Servers of plugins and subagents

experimental_mcpConnector() connects MCP servers given as .mcp.json writes them: command, args, env and cwd for stdio, url (with type: 'sse' for SSE) and headers for HTTP. Pass it as experimental_plugins.mcp for the servers of plugins, or as subagents.mcp for the inline servers of subagents. Each server's tools are named mcp__<server>__<tool> and carry their server in mcp, so a plugin server plugin:deploy:api gives mcp__plugin_deploy_api__<tool>, as in Claude Code, and permission rules and hook matchers name them that way.

import { Cogitator } from '@cogitator-ai/core';
import { experimental_mcpConnector } from '@cogitator-ai/mcp';

const mcp = experimental_mcpConnector({ timeout: 20_000 });
const cog = new Cogitator({
  experimental_plugins: { dirs: ['./plugins/deploy'], mcp },
  subagents: { files: true, mcp },
});

cogitator run adds the connector by itself when its config has experimental_plugins.

Tool Adapter

Convert tools between Cogitator and MCP formats manually when you need fine-grained control.

Cogitator to MCP

import { cogitatorToMCP } from '@cogitator-ai/mcp';

const mcpDef = cogitatorToMCP(calculator);

The definition carries the tool's title, annotations and a z.object() outputSchema as JSON Schema when it has them.

MCP to Cogitator

import { mcpToCogitator, wrapMCPTools } from '@cogitator-ai/mcp';

const cogTool = mcpToCogitator(mcpToolDefinition, client, {
  namePrefix: 'github_',
  descriptionTransform: (desc) => `[GitHub] ${desc}`,
});

const allTools = await wrapMCPTools(client, { namePrefix: 'fs_' });

Both take requiresApproval (see Approval for Destructive Tools) next to namePrefix and descriptionTransform.

Tool names are normalized to what every LLM provider accepts (letters, digits, _ and -, starting with a letter or _, at most 64 characters), while calls still go to the server under the original name: admin.list_users becomes admin_list_users, a longer name is cut and ends with a hash, and names of one server that would collide get a hash on the changed one. normalizeMCPToolName shows the result, and is the same function as normalizeToolName from @cogitator-ai/core (see Tool Names). Give each server its own namePrefix when an agent uses several, as two servers can both have a search tool. Input schemas with $ref keep their $defs, so the model sees nested models (such as FastMCP's Pydantic ones) in full.

Schema Conversion

The adapter includes utilities for converting between Zod schemas and JSON Schema, which is useful when working with MCP's JSON Schema-based tool definitions:

import { zodToJsonSchema, jsonSchemaToZod } from '@cogitator-ai/mcp';
import { z } from 'zod';

const schema = z.object({
  query: z.string().describe('Search query'),
  limit: z.number().int().min(1).max(100).optional(),
});

const jsonSchema = zodToJsonSchema(schema);

const zodSchema = jsonSchemaToZod({
  type: 'object',
  properties: {
    query: { type: 'string', description: 'Search query' },
    limit: { type: 'integer', minimum: 1, maximum: 100 },
  },
  required: ['query'],
});

MCP Apps

MCP Apps (extension io.modelcontextprotocol/ui) let a tool come with an interactive page: a ui:// resource of type text/html;profile=mcp-app that a host such as Claude, ChatGPT, VS Code or Cogitator Studio shows in a sandboxed frame for the tool's calls, given the call's arguments and result. The page can call tools of its server through the host.

Serving an app

Give a tool an app with mcpApp(). An MCPServer that serves the tool lists it with _meta.ui.resourceUri (and the older flat _meta['ui/resourceUri']), serves the page at its URI and declares the extension in its capabilities:

import { tool } from '@cogitator-ai/core';
import { MCPServer, mcpApp } from '@cogitator-ai/mcp';
import { z } from 'zod';

const chart = mcpApp({
  uri: 'ui://sales/chart',
  name: 'Sales chart',
  html: chartHtml,
  csp: { resourceDomains: ['https://cdn.jsdelivr.net'] },
  prefersBorder: true,
});

const showSales = tool({
  name: 'show_sales',
  description: 'Shows the sales of a year as a chart',
  parameters: z.object({ year: z.number() }),
  app: chart,
  execute: async ({ year }) => salesOf(year),
});

const refreshSales = tool({
  name: 'refresh_sales',
  description: 'Reloads the sales, for the chart',
  parameters: z.object({ year: z.number() }),
  app: mcpApp({ uri: 'ui://sales/chart', html: chartHtml, visibility: ['app'] }),
  execute: async ({ year }) => salesOf(year),
});

const server = new MCPServer({ name: 'sales', version: '1.0.0', transport: 'http', port: 3000 });
server.registerTools([showSales, refreshSales]);
await server.start();

mcpApp({ uri, html, name?, description?, csp?, permissions?, domain?, prefersBorder?, visibility? }) takes the page as a string or a function that builds it on each read. csp declares the origins the page reaches (connectDomains, resourceDomains, frameDomains, baseUriDomains), permissions the browser features it asks for (camera, microphone, geolocation, clipboardWrite), domain a dedicated origin in the format its host documents and prefersBorder whether it wants a border. They go to _meta.ui of the resource and of its content. visibility says who may call the tool: model, the agent, and app, its page, both by default. A tool with visibility: ['app'] is offered to no agent and serves its page only. server.registerApp({ uri, html, ... }) serves an app on its own, for tools that only point at it, and server.getRegisteredApps() lists the URIs served.

serveAgents takes apps, an app per agent name, for the agent's tool.

Using a server's apps

MCPClient tells servers it takes apps (turn it off with apps: false). A tool of a server that points at an app carries it as its app, and a tool visible to apps only (_meta.ui.visibility: ['app'], with an app of its own or none) is left out of getTools(). callTool of an app reaches only the tools whose visibility has app, or names none:

const client = await MCPClient.connect({ transport: 'http', url: 'http://localhost:3000/mcp' });

const tools = await client.getTools();
const show = tools.find((entry) => entry.name === 'show_sales');

const app = await show?.app?.read();
// { uri: 'ui://sales/chart', mimeType: 'text/html;profile=mcp-app', html, csp, prefersBorder }

await show?.app?.callTool?.('refresh_sales', { year: 2025 });
MemberWhat it does
tool.app.resourceUri, tool.app.visibilityThe app's ui:// URI and who may call the tool
tool.app.read()The page and its csp, permissions, domain and prefersBorder, the content's _meta.ui over the listing's
tool.app.callTool(name, args)Calls a tool of the same server for the page, only a tool open to apps, the result as the server sent it (content, structuredContent, isError), a structuredContent that is no object as { result: value }
tool.app.requiresApproval(name)Whether that tool is destructive (destructiveHint), so a host asks the person first
client.getToolApp(name)The app of the server's tool name, undefined for one without
client.readApp(uri)Reads an app by URI, refusing a resource that is not ui:// and text/html;profile=mcp-app
client.callToolForApp(name, args)What callTool of an app does

A host renders the page: Cogitator Studio does it for every tool call with an app, see Studio. toolAppRefOf(meta) reads the app a tool's _meta points at, and MCP_APPS_EXTENSION and MCP_APP_MIME_TYPE are the extension's identifier and MIME type.

Claude Desktop Integration

To use your Cogitator tools in Claude Desktop, run an MCP server with stdio transport and add it to your Claude config:

claude_desktop_config.json
{
  "mcpServers": {
    "my-cogitator-tools": {
      "command": "node",
      "args": ["./dist/mcp-server.js"]
    }
  }
}
mcp-server.ts
import { MCPServer } from '@cogitator-ai/mcp';
import { calculator, webSearch } from './tools';

const server = new MCPServer({
  name: 'my-cogitator-tools',
  version: '1.0.0',
  transport: 'stdio',
});

server.registerTools([calculator, webSearch]);
await server.start();

On this page