import type { Tool, ToolContract, ToolResultOf, ToolContext, MatbotPluginSpec } from '@matatbread/matbot-plugin-api'; import { PLUGIN_API_VERSION, refusalMessage } from '@matatbread/matbot-plugin-api'; import { headersSchema } from '@matatbread/matbot-tool-http'; import { RemoteMcpManager } from './manager.js'; import { gateRemoteHeaders, type RemoteHeaders } from './headers.js'; // Connecting a server is privileged — it registers a remote party's tools for the rest of the session — // so it declares a gate (`mcp_action.add`), as does disconnecting one (`mcp_action.remove`). How that // acceptance is obtained is the installation's `PermissionGate`, not this plugin's: the default asks, // and a non-interactive caller gets the `fallback: false` each site declares. Qualified by the TOOL // name, so one answer covers this plugin and node's `mcp`, which registers the same tool name. declare module '@matatbread/matbot-plugin-api' { interface ToolContracts { // Declared identically to the node `mcp` plugin (which hard-deps and overrides this tool with a // local+remote superset): a shared tool name is one merged `ToolContracts` entry, so both declarations // must match. Standalone (browser) mcp-http implements only the `remote` add — a `local` call there is // a graceful runtime error. mcp_action: | ToolContract<{ message: string; tools: string[]; instructions?: string }, { action: 'add'; name: string; type: 'local'; command: string; args?: string[]; env?: Record; proxyToolName?: string } | { action: 'add'; name: string; type: 'remote'; endpoint: string; headers?: Record; proxyToolName?: string }> | ToolContract<{ servers: unknown[] }, { action: 'list' }> | ToolContract<{ message: string }, { action: 'remove'; name: string }>; } } type McpRemoteAction = | { action: 'add'; name: string; endpoint: string; headers?: RemoteHeaders; proxyToolName?: string } | { action: 'list' } | { action: 'remove'; name: string }; function remoteMcpActionTool(manager: RemoteMcpManager): Tool> { return { name: 'mcp_action', description: `Manage remote MCP (Model Context Protocol) server connections over HTTP. An MCP server exposes a set of tools; once connected, each is registered under \`mcp____\` (the \`mcp____\` prefix is overridable per server via \`proxyToolName\`) and is callable until you remove it. This is the cross-platform (browser + Node) build: it speaks JSON-RPC over HTTP POST (with optional SSE response streaming). Local stdio servers are not available here — they need the Node mcp plugin. ACTIONS add — Connect a remote server and register its tools. Validated before saving; some servers return usage 'instructions' on connect, surfaced in the result and by 'list'. A header can carry a credential without it entering the conversation or the saved config: { "Authorization": { "Vault": "Bearer \${ACME_API_KEY}" } } sends that stored key. The user is asked before a key is sent to the server's origin. list — Show connected servers, their tools, and any instructions. remove — Disconnect a server and forget it; its proxy tools are unregistered immediately.`, inputSchema: { type: 'object', required: ['action'], properties: { action: { type: 'string', enum: ['add', 'list', 'remove'], description: 'add: connect a server. list: show servers. remove: disconnect.' }, name: { type: 'string', pattern: '^[a-z][a-z0-9_-]*$', description: 'Short lowercase server id (add/remove); becomes the tool-name prefix.' }, // Required by the shared contract (node `mcp` also has 'local'), so the typed validator rejects an // add without it; advertised here so the model is told to send it. type: { type: 'string', enum: ['remote'], description: 'add only: always "remote" — this build connects to HTTP endpoints only.' }, endpoint: { type: 'string', description: 'add only: the MCP HTTP endpoint URL.' }, headers: { ...headersSchema, description: `add only: HTTP headers sent with every request to the server. ${headersSchema.description}` }, proxyToolName: { type: 'string', description: 'add only: prefix for this server\'s tool names, replacing the default "mcp____". Persisted; reconnects keep it.' }, }, }, executor: { async *execute(input: unknown, ctx: ToolContext) { const act = input as McpRemoteAction; switch (act.action) { case 'add': { if (!act.name || !act.endpoint) { yield { type: 'error', message: 'add requires "name" and "endpoint".' }; return; } const permit = await ctx.gate({ gate: 'add', subject: act.name, fallback: false, label: `Connect to MCP server **"${act.name}"** at ${act.endpoint}?\n\n_Its tools are registered and callable until you remove it._` }); if (!permit.allowed) { yield { type: 'result', value: { message: refusalMessage(permit) } }; return; } const secrets = await gateRemoteHeaders(act.endpoint, act.headers, ctx); if (!secrets.ok) { yield { type: 'error', message: secrets.message }; return; } yield { type: 'stdout', chunk: `Connecting to MCP server "${act.name}"...\n` }; try { const r = await manager.add({ name: act.name, endpoint: act.endpoint, ...(act.headers !== undefined ? { headers: act.headers } : {}), ...(act.proxyToolName !== undefined ? { proxyToolName: act.proxyToolName } : {}) }); yield { type: 'result', value: { message: `Connected. ${r.tools.length} tool(s) registered.`, tools: r.tools, ...(r.instructions !== undefined ? { instructions: r.instructions } : {}) } }; } catch (e) { yield { type: 'error', message: `Failed to connect to "${act.name}": ${String(e)}` }; } return; } case 'list': yield { type: 'result', value: { servers: manager.list() } }; return; case 'remove': { if (!act.name) { yield { type: 'error', message: 'remove requires "name".' }; return; } const permit = await ctx.gate({ gate: 'remove', subject: act.name, fallback: false, label: `Remove MCP server **"${act.name}"**?` }); if (!permit.allowed) { yield { type: 'result', value: { message: refusalMessage(permit) } }; return; } const ok = await manager.remove(act.name); yield { type: 'result', value: { message: ok ? `"${act.name}" disconnected and removed.` : `No MCP server named "${act.name}".` } }; return; } default: yield { type: 'error', message: `Unknown mcp_action "${(act as { action: string }).action}".` }; } }, }, }; } export function createMcpHttpPlugin(): MatbotPluginSpec { let manager: RemoteMcpManager | undefined; return { apiVersion: PLUGIN_API_VERSION, manifest: { description: 'Cross-platform remote MCP client (HTTP/SSE). Registers mcp_action and the McpRemoteService delegation service.' }, async setup(services) { manager = new RemoteMcpManager(services, services.settings()); await services.register('McpRemoteService', manager); services.tools.register(remoteMcpActionTool(manager)); // Not awaited, as in the node mcp plugin: setup() is registration, and a server that is slow or // unreachable must not hold the rest of the boot. Its proxy tools appear when it answers. void manager.reconnectPersisted((name, err) => console.warn(`[mcp-http] Failed to reconnect "${name}":`, err)) .catch((e: unknown) => console.warn('[mcp-http] Reconnect failed:', e)); }, async teardown() { manager?.closeAll(); }, }; } export const plugin: MatbotPluginSpec = createMcpHttpPlugin();