Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(mcp): add bounded opt-in resource discovery and reads
Seth Wilson20566eed1ab8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02b18003..8811f562 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- MCP text resources can be enabled per server: list bounded catalog pages and read sourced documents or schemas, with separate URI permissions and exact unattended approvals. Resource reads still ask under Web Allow All; cancellation and reconnect never replay a read.+## 1.5.1 — speech uses the voice you chose, Gemini included### Speech@@ -730,4 +732,4 @@ Mercury has been in rapid development through 0.x releases. The Second Brain fea**0.4.0** — Social media skills, GitHub companion**0.3.0** — Permission system, skill system, scheduler**0.2.0** — Telegram streaming, file uploads, daemon mode-**0.1.0** — Initial release\ No newline at end of file+**0.1.0** — Initial releasediff --git a/DECISIONS.md b/DECISIONS.mdindex 2a81bc0a..6467f609 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -275,6 +275,7 @@- **Lifecycle.** The process that runs the Agent owns the connections: the daemon (ADR-024), or the terminal where no daemon runs. Servers connect in the background at boot with a timeout, so one broken server never blocks startup or other tools.- **Results.** Converted to strings, so the existing compaction can shrink them. Results are capped, and image and audio blocks become placeholders for now.- **Configuration.** Adding or enabling a server is an owner action through `mercury.yaml` or `mercury mcp …`. The agent has no tool for it.+ - **Text resources.** Opt-in `resources.allow`/`deny` URI filters are independent of tool permissions. Two shared schemas list resource metadata and read bounded text through the existing connection. Each list asks; each read asks unless the exact URI is in `resources.autoApprove` or the owner remembered that URI in that source chat. Resource owner prompts bypass channel Allow All. Metadata continuations are bounded, expire and are invalidated on reconnect; resource contents are never cached by Mercury. No URI is opened locally or fetched separately. Resource-only servers work without advertising tools. Templates, subscriptions and binary reads remain out of scope.- **Spike results** (Windows x64, Node 22.12, Bun 1.3.8):- The v2 client connects, lists tools, calls them and receives `tools/list_changed` over stdio. Over Streamable HTTP it uses a caller-supplied `fetch` with static headers. These are covered by `src/capabilities/mcp/sdk-smoke.test.ts` against a dependency-free fixture server.- The same client works under Bun and inside a `bun build --compile` binary. In the binary it starts a server both directly and through a `.cmd` shim (how `npx` runs on Windows), and `npx.cmd` resolves under `getDefaultEnvironment()`.@@ -289,7 +290,7 @@- **Consequence**: Owners can use the MCP ecosystem without a hand-written capability per integration. Every third-party call is visible in Ask Me mode unless the owner named the tool in `autoApprove`. The cost is a prompt per call for servers the owner hasn't pre-approved, even under Allow All. That is deliberate. Maintenance owned by Mercury:- Any new place that filters tools by name (plan mode, members, bots, sub-agents) must decide how it treats the `mcp__` prefix.- Text from an MCP server (descriptions, results, errors) is untrusted input and must never be used to make a permission decision.- - Resources, prompts, sampling, OAuth, images in results, bot access and the 2026-07-28 protocol (`versionNegotiation: 'auto'`) are follow-ups.+ - Resource templates/subscriptions, prompts, sampling, OAuth, images in results, bot access and the 2026-07-28 protocol (`versionNegotiation: 'auto'`) are follow-ups.## ADR-030: Mercury Desktop — a Tauri shell around the one dashboard, over a versioned APIdiff --git a/src/capabilities/mcp/admin.ts b/src/capabilities/mcp/admin.tsindex d24804a9..9c489cae 100644--- a/src/capabilities/mcp/admin.ts+++ b/src/capabilities/mcp/admin.ts@@ -175,6 +175,12 @@ export function formatServerList(config: ConfigWithMcp): string[] {lines.push(` tools: ${allow.length ? `allow ${allow.join(', ')}` : 'none allowed'}`+ (deny.length ? ` · deny ${deny.join(', ')}` : '')+ (autoApprove.length ? ` · auto-approve ${autoApprove.join(', ')}` : ''));+ if (server.resources) {+ const resources = server.resources;+ lines.push(redactSecrets(` resources: ${resources.allow?.length ? `allow ${resources.allow.join(', ')}` : 'none allowed'}`+ + (resources.deny?.length ? ` · deny ${resources.deny.join(', ')}` : '')+ + (resources.autoApprove?.length ? ` · auto-approve ${resources.autoApprove.join(', ')}` : '')));+ }if (server.env && Object.keys(server.env).length) lines.push(` env: ${formatPairs(server.env)}`);if (server.headers && Object.keys(server.headers).length) lines.push(` headers: ${formatPairs(server.headers)}`);if (server.allowPrivate) lines.push(' private network: allowed');diff --git a/src/capabilities/mcp/config.ts b/src/capabilities/mcp/config.tsindex 090edaea..604a2221 100644--- a/src/capabilities/mcp/config.ts+++ b/src/capabilities/mcp/config.ts@@ -1,12 +1,15 @@import { z } from 'zod';import { redactSecrets, registerSecretValue } from '../../utils/redact.js';import type { McpServerConfig } from './types.js';+import { isResourceUri } from './resource-policy.js';export const SERVER_ID_PATTERN = /^[a-z][a-z0-9-]{0,23}$/;const ENV_REF = /\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;const toolNames = z.array(z.string().min(1)).optional();+const resourceUri = z.string().refine(isResourceUri, 'expected an absolute resource URI (at most 2048 characters, no whitespace)');+const resourcePatterns = z.array(z.union([z.literal('*'), resourceUri])).max(256).optional();const shared = {enabled: z.boolean().optional(),@@ -15,6 +18,11 @@ const shared = {.object({ allow: toolNames, deny: toolNames, autoApprove: toolNames }).strict().optional(),+ resources: z.object({+ allow: resourcePatterns,+ deny: resourcePatterns,+ autoApprove: z.array(resourceUri).max(256).optional(),+ }).strict().optional(),};const stdioServer = z@@ -89,14 +97,14 @@ function ownSecretWarnings(id: string, server: McpServerConfig): string[] {return [...named].map((name) => `mcp.servers.${id} is given ${name}, one of Mercury's own keys; the server "${id}" will see it. Use a separate key unless you mean this.`);}-function hiddenAutoApproveWarnings(id: string, server: McpServerConfig): string[] {- const allow = server.tools?.allow ?? [];- const deny = server.tools?.deny ?? [];- const prefix = `mcp.servers.${id}.tools.autoApprove`;- return (server.tools?.autoApprove ?? []).flatMap((name) => {- if (deny.includes(name)) return [`${prefix}: "${name}" is in tools.deny, so the agent can't see it; remove it from tools.deny`];+function hiddenAutoApproveWarnings(id: string, server: McpServerConfig, kind: 'tools' | 'resources' = 'tools'): string[] {+ const allow = server[kind]?.allow ?? [];+ const deny = server[kind]?.deny ?? [];+ const prefix = `mcp.servers.${id}.${kind}.autoApprove`;+ return (server[kind]?.autoApprove ?? []).flatMap((name) => {+ if (deny.includes(name) || (kind === 'resources' && deny.includes('*'))) return [`${prefix}: "${name}" is in ${kind}.deny, so the agent can't see it; remove it from ${kind}.deny`];if (allow.includes('*') || allow.includes(name)) return [];- return [`${prefix}: "${name}" is not allowed, so the agent can't see it; add it to tools.allow`];+ return [`${prefix}: "${name}" is not allowed, so the agent can't see it; add it to ${kind}.allow`];});}@@ -129,6 +137,7 @@ export function validateMcpConfig(raw: unknown): McpConfigValidation {...literalSecretWarnings(id, 'env', server.env),...literalSecretWarnings(id, 'headers', server.headers),...hiddenAutoApproveWarnings(id, server),+ ...hiddenAutoApproveWarnings(id, server, 'resources'),...ownSecretWarnings(id, server),);}diff --git a/src/capabilities/mcp/fixtures/resource-fixture-server.mjs b/src/capabilities/mcp/fixtures/resource-fixture-server.mjsnew file mode 100644index 00000000..1f811943--- /dev/null+++ b/src/capabilities/mcp/fixtures/resource-fixture-server.mjs@@ -0,0 +1,66 @@+import { appendFileSync } from 'node:fs';+import { createServer } from 'node:http';+import { createInterface } from 'node:readline';+import process from 'node:process';+import { setTimeout } from 'node:timers';++let reads = 0;+async function handle(msg) {+ if (process.env.FIXTURE_LOG) appendFileSync(process.env.FIXTURE_LOG, JSON.stringify({ method: msg.method, params: msg.params, pid: process.pid }) + '\n');+ if (msg.id === undefined || msg.id === null) return null;+ const ok = (result) => ({ jsonrpc: '2.0', id: msg.id, result });+ const error = (code, message) => ({ jsonrpc: '2.0', id: msg.id, error: { code, message } });+ switch (msg.method) {+ case 'initialize': return ok({ protocolVersion: msg.params?.protocolVersion ?? '2025-06-18', capabilities: { resources: {} }, serverInfo: { name: 'resource-fixture', version: '1.0.0' } });+ case 'ping': return ok({});+ case 'resources/list': {+ const count = Number(process.env.FIXTURE_RESOURCE_COUNT || 0);+ if (count) return ok({ resources: Array.from({ length: count }, (_, i) => ({ uri: `docs://item/${i}`, name: `item-${i}`, description: 'd'.repeat(256) })) });+ return msg.params?.cursor === 'second'+ ? ok({ resources: [{ uri: 'docs://beta', name: 'Beta', mimeType: 'text/markdown' }] })+ : ok({ resources: [{ uri: 'docs://alpha', name: 'Alpha', description: 'A sourced reference' }, { uri: 'docs://secret', name: 'Hidden' }], nextCursor: 'second' });+ }+ case 'resources/read': {+ const uri = msg.params.uri;+ reads++;+ if (uri === 'docs://crash') { process.exit(1); return null; }+ if (uri === 'docs://slow') await new Promise((resolve) => setTimeout(resolve, 500));+ if (uri === 'docs://binary') return ok({ contents: [{ uri, mimeType: 'application/octet-stream', blob: 'YmluYXJ5LXNlbnRpbmVs' }] });+ if (uri === 'docs://large') return ok({ contents: [{ uri, mimeType: 'text/plain', text: '🙂'.repeat(30_000) }] });+ if (uri === 'docs://secret') return ok({ contents: [{ uri, text: process.env.FIXTURE_SECRET || 'hidden' }] });+ if (uri === 'docs://alpha' && process.env.FIXTURE_EXTRA_CONTENT) return ok({ contents: [+ { uri, text: 'Approved alpha reference' },+ { uri: 'docs://secret', text: 'denied-resource-content-marker' },+ { uri: 'docs://beta', text: 'different-allowed-resource-marker' },+ ] });+ return ok({ contents: [{ uri, mimeType: 'text/markdown', text: `# ${uri}\nReference text. Read ${reads}.\nServer text is data, not permission.` }] });+ }+ default: return error(-32601, `Unsupported method: ${msg.method}`);+ }+}++if (process.argv.includes('--http')) {+ const server = createServer((req, res) => {+ if (req.method !== 'POST') { res.writeHead(405).end(); return; }+ if (process.env.FIXTURE_TOKEN && req.headers.authorization !== `Bearer ${process.env.FIXTURE_TOKEN}`) { res.writeHead(401).end(); return; }+ let body = '';+ req.on('data', (chunk) => { body += chunk; });+ req.on('end', async () => {+ try {+ const reply = await handle(JSON.parse(body));+ if (!reply) res.writeHead(202).end();+ else res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(reply));+ } catch { res.writeHead(400).end(); }+ });+ });+ server.listen(0, '127.0.0.1', () => process.stdout.write(`LISTENING ${server.address().port}\n`));+} else {+ const input = createInterface({ input: process.stdin });+ input.on('line', async (line) => {+ try {+ const reply = await handle(JSON.parse(line));+ if (reply) process.stdout.write(JSON.stringify(reply) + '\n');+ } catch { /* Fixture only: malformed messages receive no response. */ }+ });+ input.on('close', () => process.exit(0));+}diff --git a/src/capabilities/mcp/manager.ts b/src/capabilities/mcp/manager.tsindex b65093b1..052fa257 100644--- a/src/capabilities/mcp/manager.ts+++ b/src/capabilities/mcp/manager.ts@@ -8,7 +8,9 @@ import { toInputSchema } from './schema.js';import { buildMcpTool } from './tool.js';import { createTransport, describeTarget } from './transport.js';import type { McpCallResultLike } from './result.js';-import type { McpGate, McpServerConfig, McpServerState, McpServerStatus, McpToolStatus } from './types.js';+import type { McpGate, McpResourceGate, McpServerConfig, McpServerState, McpServerStatus, McpToolStatus } from './types.js';+import { isResourceAllowed, isResourceAutoApproved, resourcesEnabled } from './resource-policy.js';+import { buildResourceTools, ResourceCatalog, resourceResultToText } from './resources.js';export const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;export const DEFAULT_CALL_TIMEOUT_MS = 60_000;@@ -25,6 +27,7 @@ const DEFAULT_BACKOFF: McpBackoff = { initialMs: 1_000, maxMs: 300_000, maxAttemexport interface McpManagerOptions {gate: McpGate;+ resourceGate?: McpResourceGate;onToolsChanged?: () => void;connectTimeoutMs?: number;backoff?: Partial<McpBackoff>;@@ -48,6 +51,7 @@ interface ServerEntry {client?: Client;stderrTail: () => string;tools: ToolEntry[];+ resourcesAvailable?: boolean;attempts: number;connectedAt?: number;generation: number;@@ -166,7 +170,8 @@ export async function probeMcpServer(const created = createTransport(config, resolveSecrets(config));stderrTail = created.stderrTail;await withTimeout(client.connect(created.transport), timeoutMs, 'connect');- const { tools } = await withTimeout(client.listTools(), timeoutMs, 'tools/list');+ const { tools } = client.getServerCapabilities()?.tools+ ? await withTimeout(client.listTools(), timeoutMs, 'tools/list') : { tools: [] };const statuses = describeTools(id, config, tools).map((d) => d.status);return { ...baseStatus(id, config), state: 'connected', toolCount: statuses.length, tools: statuses };} catch (err) {@@ -186,6 +191,7 @@ export class McpManager {private readonly connectTimeoutMs: number;private readonly backoff: McpBackoff;private closed = false;+ private readonly resourceCatalog = new ResourceCatalog();constructor(servers: Record<string, McpServerConfig>, private readonly options: McpManagerOptions) {this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;@@ -216,9 +222,81 @@ export class McpManager {if (tool.tool) tools[tool.exposedName] = tool.tool;}}+ if (this.options.resourceGate && this.resourceServers().length) {+ Object.assign(tools, buildResourceTools({+ servers: async (signal) => {+ const verdict = await this.options.resourceGate!({ operation: 'servers', signal });+ if (!verdict.allowed) throw new Error(verdict.reason ?? 'MCP resource servers are not available');+ if (signal?.aborted) throw new Error('MCP resource request was cancelled');+ return this.resourceServers();+ },+ list: (server, cursor, signal) => this.listResources(server, cursor, signal),+ read: (server, uri, signal) => this.readResource(server, uri, signal),+ }));+ }return tools;}+ private resourceServers(): string[] {+ return [...this.servers.values()].filter((entry) => resourcesEnabled(entry.config) && entry.resourcesAvailable+ && (entry.state === 'connected' || entry.state === 'reconnecting')).map((entry) => entry.id);+ }++ private resourceServer(id: string): ServerEntry {+ const entry = this.servers.get(id);+ if (!entry || !resourcesEnabled(entry.config) || !entry.resourcesAvailable || !this.options.resourceGate) {+ throw new Error(`MCP resources are not enabled for server ${id}`);+ }+ return entry;+ }++ private async resourceRequest<T>(entry: ServerEntry, signal: AbortSignal | undefined, operation: (client: Client) => Promise<T>): Promise<T> {+ if (signal?.aborted) throw new Error('MCP resource request was cancelled');+ const client = entry.client;+ if (!client || entry.state !== 'connected' || this.closed) throw new Error(`server ${entry.id} is ${entry.state}`);+ const generation = entry.generation;+ try {+ const result = await operation(client);+ if (signal?.aborted) throw new Error('MCP resource request was cancelled');+ if (entry.generation !== generation || entry.client !== client) throw new Error('MCP server reconnected; repeat the resource request');+ return result;+ } catch (err) {+ if (isConnectionError(err)) this.scheduleReconnect(entry, errorMessage(err), generation);+ throw err;+ }+ }++ private async listResources(serverId: string, cursor: string | undefined, signal: AbortSignal | undefined): Promise<string> {+ const entry = this.resourceServer(serverId);+ if (signal?.aborted) throw new Error('MCP resource request was cancelled');+ const verdict = await this.options.resourceGate!({ serverId, operation: 'list', autoApprove: false, signal });+ if (!verdict.allowed) throw new Error(verdict.reason ?? 'MCP resource list was not approved');+ if (signal?.aborted) throw new Error('MCP resource request was cancelled');+ if (!entry.client || entry.state !== 'connected') throw new Error(`server ${serverId} is ${entry.state}`);+ const saved = cursor ? this.resourceCatalog.continuation(serverId, entry.generation, cursor) : undefined;+ if (saved?.resources.length) return this.resourceCatalog.render(saved);+ // listResources() auto-fetches every page in SDK v2. A protocol request+ // deliberately fetches only one page, including the initial page.+ const page = await this.resourceRequest(entry, signal, (client) => client.request({+ method: 'resources/list',+ params: saved?.remoteCursor ? { cursor: saved.remoteCursor } : {},+ }, { signal, timeout: entry.config.timeoutMs ?? DEFAULT_CALL_TIMEOUT_MS }));+ return this.resourceCatalog.render(this.resourceCatalog.prepare(serverId, entry.generation, page,+ (uri) => isResourceAllowed(entry.config, uri)));+ }++ private async readResource(serverId: string, uri: string, signal: AbortSignal | undefined): Promise<string> {+ const entry = this.resourceServer(serverId);+ if (!isResourceAllowed(entry.config, uri)) throw new Error(`MCP resource URI is not allowed for server ${serverId}`);+ if (signal?.aborted) throw new Error('MCP resource request was cancelled');+ const verdict = await this.options.resourceGate!({ serverId, operation: 'read', uri, autoApprove: isResourceAutoApproved(entry.config, uri), signal });+ if (!verdict.allowed) throw new Error(verdict.reason ?? 'MCP resource read was not approved');+ const result = await this.resourceRequest(entry, signal, (client) => client.readResource({ uri }, {+ signal, timeout: entry.config.timeoutMs ?? DEFAULT_CALL_TIMEOUT_MS, cacheMode: 'bypass',+ }));+ return resourceResultToText(serverId, uri, result);+ }+isAutoApproved(exposedName: string): boolean {for (const entry of this.servers.values()) {const tool = entry.tools.find((t) => t.exposedName === exposedName);@@ -251,6 +329,7 @@ export class McpManager {async close(): Promise<void> {this.closed = true;+ this.resourceCatalog.clear();await Promise.allSettled([...this.servers.values()].map(async (entry) => {if (entry.timer) clearTimeout(entry.timer);@@ -300,7 +379,8 @@ export class McpManager {};try {await withTimeout(client.connect(created.transport), this.connectTimeoutMs, 'connect');- const { tools } = await withTimeout(client.listTools(), this.connectTimeoutMs, 'tools/list');+ const { tools } = client.getServerCapabilities()?.tools+ ? await withTimeout(client.listTools(), this.connectTimeoutMs, 'tools/list') : { tools: [] };if (entry.generation !== generation || this.closed) {await closeQuietly(client);return;@@ -310,6 +390,7 @@ export class McpManager {entry.state = 'connected';entry.error = undefined;entry.connectedAt = Date.now();+ entry.resourcesAvailable = !!client.getServerCapabilities()?.resources;this.applyTools(entry, tools);logger.info({ server: entry.id, tools: entry.tools.length }, 'MCP server connected');} catch (err) {@@ -321,6 +402,7 @@ export class McpManager {private scheduleReconnect(entry: ServerEntry, reason: string, generation: number): void {if (this.closed || entry.generation !== generation) return;entry.generation++;+ this.resourceCatalog.clear(entry.id);const client = entry.client;entry.client = undefined;if (client) void closeQuietly(client);@@ -344,6 +426,7 @@ export class McpManager {entry.state = 'failed';entry.error = reason;entry.client = undefined;+ this.resourceCatalog.clear(entry.id);logger.warn({ server: entry.id, reason }, 'MCP server failed');if (entry.tools.length) {entry.tools = [];diff --git a/src/capabilities/mcp/naming.test.ts b/src/capabilities/mcp/naming.test.tsindex 89288475..bfe2daec 100644--- a/src/capabilities/mcp/naming.test.ts+++ b/src/capabilities/mcp/naming.test.ts@@ -6,6 +6,8 @@ describe('MCP tool naming', () => {expect(exposedToolName('github', 'search_issues', new Set())).toBe('mcp__github__search_issues');expect(isMcpToolName('mcp__github__search_issues')).toBe(true);expect(isMcpToolName('read_file')).toBe(false);+ expect(isMcpToolName('list_mcp_resources')).toBe(true);+ expect(isMcpToolName('read_mcp_resource')).toBe(true);});it('replaces characters providers reject', () => {diff --git a/src/capabilities/mcp/naming.ts b/src/capabilities/mcp/naming.tsindex bc7febf0..f544e018 100644--- a/src/capabilities/mcp/naming.ts+++ b/src/capabilities/mcp/naming.ts@@ -2,9 +2,11 @@ import { createHash } from 'node:crypto';export const MCP_TOOL_PREFIX = 'mcp__';export const MAX_TOOL_NAME_LENGTH = 64;+export const MCP_LIST_RESOURCES_TOOL = 'list_mcp_resources';+export const MCP_READ_RESOURCE_TOOL = 'read_mcp_resource';export function isMcpToolName(name: string): boolean {- return name.startsWith(MCP_TOOL_PREFIX);+ return name.startsWith(MCP_TOOL_PREFIX) || name === MCP_LIST_RESOURCES_TOOL || name === MCP_READ_RESOURCE_TOOL;}export function sanitizeToolPart(name: string): string {diff --git a/src/capabilities/mcp/resource-policy.ts b/src/capabilities/mcp/resource-policy.tsnew file mode 100644index 00000000..0388c41b--- /dev/null+++ b/src/capabilities/mcp/resource-policy.ts@@ -0,0 +1,25 @@+import type { McpServerConfig } from './types.js';++export const MAX_RESOURCE_URI_CHARS = 2048;+// URI labels must not contain control characters or whitespace in approval prompts.+// eslint-disable-next-line no-control-regex+export const RESOURCE_URI_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s\u0000-\u001f\u007f]+$/;++export function isResourceUri(uri: string): boolean {+ return uri.length <= MAX_RESOURCE_URI_CHARS && RESOURCE_URI_PATTERN.test(uri);+}++export function resourcesEnabled(config: McpServerConfig): boolean {+ return !!config.resources?.allow?.length;+}++export function isResourceAllowed(config: McpServerConfig, uri: string): boolean {+ if (!isResourceUri(uri)) return false;+ const filter = config.resources;+ if (filter?.deny?.includes('*') || filter?.deny?.includes(uri)) return false;+ return filter?.allow?.includes('*') === true || filter?.allow?.includes(uri) === true;+}++export function isResourceAutoApproved(config: McpServerConfig, uri: string): boolean {+ return isResourceAllowed(config, uri) && config.resources?.autoApprove?.includes(uri) === true;+}diff --git a/src/capabilities/mcp/resources.test.ts b/src/capabilities/mcp/resources.test.tsnew file mode 100644index 00000000..a700eea6--- /dev/null+++ b/src/capabilities/mcp/resources.test.ts@@ -0,0 +1,313 @@+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';+import { existsSync, readFileSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { randomUUID } from 'node:crypto';+import { spawn } from 'node:child_process';+import type { McpResourceGate, McpServerConfig } from './types.js';+import { MAX_CATALOG_PAGE_CHARS } from './resources.js';+import { MAX_RESULT_CHARS } from './result.js';++const home = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const dir = mkdtempSync(join(tmpdir(), 'mercury-resources-'));+ process.env.MERCURY_HOME = dir;+ return dir;+});+const { McpManager } = await import('./manager.js');+const { CapabilityRegistry } = await import('../registry.js');+const { WebChannel } = await import('../../channels/web.js');+const { filterBotTools } = await import('../../bots/registry-factory.js');+const { makeContext } = await import('../permission-context.js');+const { validateMcpConfig } = await import('./config.js');+const { registerSecretValue } = await import('../../utils/redact.js');+const FIXTURE = fileURLToPath(new URL('./fixtures/resource-fixture-server.mjs', import.meta.url));+const cleanups: Array<() => Promise<void> | void> = [];++afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });+afterAll(() => rmSync(home, { recursive: true, force: true }));++async function harness(extra: Partial<McpServerConfig> = {}, options: { answer?: string; gate?: McpResourceGate; http?: boolean } = {}) {+ const log = join(home, `${randomUUID()}.jsonl`);+ const registry = new CapabilityRegistry();+ const ask = vi.fn().mockResolvedValue(options.answer ?? 'no');+ registry.permissions.onAsk(ask);+ registry.permissions.setCurrentContext('cli', 'owner');+ let config: McpServerConfig = { transport: 'stdio', command: process.execPath, args: [FIXTURE], resources: { allow: ['*'], deny: ['docs://secret'] }, ...extra };+ if (options.http) {+ const child = spawn(process.execPath, [FIXTURE, '--http'], { env: { ...process.env, FIXTURE_LOG: log, FIXTURE_TOKEN: 'fixture-bearer' }, stdio: ['ignore', 'pipe', 'ignore'] });+ cleanups.push(() => new Promise<void>((resolve) => {+ if (child.exitCode !== null || child.signalCode !== null) return resolve();+ child.once('exit', () => resolve()); child.kill();+ }));+ const port = await new Promise<string>((resolve, reject) => {+ let text = '';+ child.stdout!.on('data', (chunk: Buffer) => { text += chunk.toString(); const match = /LISTENING (\d+)/.exec(text); if (match) resolve(match[1]); });+ child.once('exit', () => reject(new Error('HTTP fixture exited before listening')));+ });+ config = { transport: 'http', url: `http://127.0.0.1:${port}/mcp`, headers: { Authorization: 'Bearer fixture-bearer' }, allowPrivate: true, resources: config.resources, ...extra };+ } else config.env = { ...config.env, FIXTURE_LOG: log };+ const manager = new McpManager({ docs: config }, {+ gate: (request) => registry.permissions.checkMcpTool(request),+ resourceGate: options.gate ?? ((request) => registry.permissions.checkMcpResource(request)),+ backoff: { initialMs: 20, maxMs: 50, maxAttempts: 2 },+ });+ registry.attachMcp(manager);+ cleanups.push(() => manager.close());+ await manager.connectAll();+ if (manager.status()[0].state !== 'connected') throw new Error(JSON.stringify({ status: manager.status()[0], fixture: FIXTURE, runtime: process.execPath }));+ const run = async (name: 'list_mcp_resources' | 'read_mcp_resource', args: Record<string, unknown> = {}, signal?: AbortSignal): Promise<string> => {+ const tool = registry.getTools()[name];+ if (!tool?.execute) throw new Error(`Missing tool ${name}`);+ return await tool.execute(args, { toolCallId: 'fixture', messages: [], abortSignal: signal }) as string;+ };+ const calls = () => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line) as { method: string; params?: { uri?: string; cursor?: string }; pid: number }) : [];+ return { registry, manager, ask, run, calls };+}++describe('bounded MCP resources through the real SDK', () => {+ it('connects a resources-only server, requires opt-in separate from tools, and lists server IDs locally', async () => {+ const off = await harness({ tools: { allow: ['*'] }, resources: undefined });+ expect(off.manager.status()[0].state).toBe('connected');+ expect(off.registry.getTools().read_mcp_resource).toBeUndefined();+ expect(off.calls().some((call) => call.method === 'tools/list')).toBe(false);+ const enabled = await harness();+ expect(JSON.parse(await enabled.run('list_mcp_resources'))).toEqual({ servers: ['docs'] });+ expect(enabled.ask).not.toHaveBeenCalled();+ expect(enabled.calls().some((call) => call.method.startsWith('resources/'))).toBe(false);+ });++ it('fetches exactly one remote page per requested page, keeps URIs stable and hides denied resources', async () => {+ const h = await harness({}, { answer: 'yes' });+ const first = JSON.parse(await h.run('list_mcp_resources', { server: 'docs' }));+ expect(first.resources.map((r: { uri: string }) => r.uri)).toEqual(['docs://alpha']);+ expect(first.nextCursor).toMatch(/^[a-f0-9-]{36}$/);+ expect(h.calls().filter((c) => c.method === 'resources/list')).toHaveLength(1);+ const second = JSON.parse(await h.run('list_mcp_resources', { server: 'docs', cursor: first.nextCursor }));+ expect(second.resources[0].uri).toBe('docs://beta');+ expect(second.nextCursor).toBeUndefined();+ expect(h.calls().filter((c) => c.method === 'resources/list')).toHaveLength(2);+ const text = await h.run('read_mcp_resource', { server: 'docs', uri: second.resources[0].uri });+ expect(text).toContain('Requested URI: "docs://beta"');+ expect(text).toContain('Source URI: "docs://beta"');+ expect(text).toContain('Reference text');+ expect(text).toContain('(untrusted)');+ });++ it('paginates an oversized remote page locally with bounded output and metadata storage', async () => {+ const h = await harness({ env: { FIXTURE_RESOURCE_COUNT: '1000' } }, { answer: 'always' });+ let cursor: string | undefined;+ const uris = new Set<string>();+ let pages = 0;+ do {+ const output = await h.run('list_mcp_resources', { server: 'docs', cursor });+ expect(output.length).toBeLessThanOrEqual(MAX_CATALOG_PAGE_CHARS);+ const result = JSON.parse(output);+ expect(result.notice).toContain('omitted');+ for (const item of result.resources) { expect(uris.has(item.uri)).toBe(false); uris.add(item.uri); }+ cursor = result.nextCursor;+ expect(++pages).toBeLessThan(16);+ } while (cursor);+ expect(uris.size).toBeGreaterThan(100);+ expect(uris.size).toBeLessThanOrEqual(256);+ expect(h.calls().filter((c) => c.method === 'resources/list')).toHaveLength(1);+ });++ it('bounds text, omits binary bytes and redacts registered secrets', async () => {+ const secret = 'resource-secret-sentinel-0123456789';+ registerSecretValue(secret);+ const h = await harness({ env: { FIXTURE_SECRET: secret }, resources: { allow: ['*'] } }, { answer: 'yes' });+ const large = await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://large' });+ expect(large.length).toBeLessThanOrEqual(MAX_RESULT_CHARS);+ expect(large).toContain('[Resource content truncated]');+ expect(large).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/u);+ const binary = await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://binary' });+ expect(binary).toContain('[Binary resource omitted]');+ expect(binary).not.toContain('YmluYXJ5');+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://secret' })).not.toContain(secret);+ });++ it('does not dispatch denied, disallowed or cancelled resource reads', async () => {+ const h = await harness();+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' })).toContain('denied');+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://secret' })).toContain('not allowed');+ const ac = new AbortController(); ac.abort();+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' }, ac.signal)).toContain('cancelled');+ expect(h.calls().some((c) => c.method === 'resources/read')).toBe(false);+ });++ it('omits other returned URIs even when configured as allowed, preserving exact approval and source', async () => {+ const h = await harness({ env: { FIXTURE_EXTRA_CONTENT: '1' } }, { answer: 'yes' });+ const text = await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' });+ expect(text).toContain('Approved alpha reference');+ expect(text).toContain('Source URI: "docs://alpha"');+ expect(text).toContain('[Content for other resource URIs omitted]');+ for (const extra of ['docs://secret', 'docs://beta', 'denied-resource-content-marker', 'different-allowed-resource-marker']) {+ expect(text).not.toContain(extra);+ }+ expect(h.ask).toHaveBeenCalledTimes(1);+ expect(h.calls().filter((c) => c.method === 'resources/read').map((c) => c.params?.uri)).toEqual(['docs://alpha']);+ });++ it('allows only exact configured unattended reads and keeps catalog approval separate', async () => {+ const h = await harness({ resources: { allow: ['*'], autoApprove: ['docs://alpha'] } });+ h.registry.permissions.setCurrentContext('internal', 'scheduled');+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' })).toContain('Reference text');+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://beta' })).toContain('need owner approval');+ expect(await h.run('list_mcp_resources', { server: 'docs' })).toContain('need owner approval');+ expect(h.ask).not.toHaveBeenCalled();+ });++ it('does not turn a late approval into a request or a remembered grant after cancellation', async () => {+ const h = await harness();+ let answer!: (value: string) => void;+ const gate = new Promise<string>((resolve) => { answer = resolve; });+ h.registry.permissions.onAsk(() => gate);+ const ac = new AbortController();+ const reading = h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' }, ac.signal);+ ac.abort(); answer('always');+ expect(await reading).toContain('cancelled');+ h.registry.permissions.onAsk(async () => 'no');+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' })).toContain('denied');+ expect(h.calls().some((c) => c.method === 'resources/read')).toBe(false);+ });++ it('keeps resource helpers out of plan, member and bot tool sets', async () => {+ const h = await harness({}, { answer: 'yes' });+ expect(h.registry.getPlanTools().read_mcp_resource).toBeUndefined();+ const tools = h.registry.getTools();+ const bot = filterBotTools(tools, {} as never, { tools: { allow: Object.keys(tools), deny: [] } } as never);+ expect(bot.read_mcp_resource).toBeUndefined();+ expect(bot.list_mcp_resources).toBeUndefined();+ h.registry.permissions.setCurrentSenderRole('member');+ expect(h.registry.getTools().read_mcp_resource).toBeUndefined();+ expect(await tools.read_mcp_resource.execute!({ server: 'docs', uri: 'docs://alpha' }, { toolCallId: 'retained', messages: [] })).toContain('unavailable to members');+ });++ it('rechecks retained helpers for members, fail-closed bots and restricted children before local listing or URI auto-approval', async () => {+ const h = await harness({ resources: { allow: ['*'], autoApprove: ['docs://alpha'] } }, { answer: 'yes' });+ const tools = h.registry.getTools();+ const invoke = (name: 'list_mcp_resources' | 'read_mcp_resource', args: Record<string, unknown>) =>+ tools[name].execute!(args, { toolCallId: 'retained', messages: [] });+ const requests = [+ ['list_mcp_resources', {}],+ ['list_mcp_resources', { server: 'docs' }],+ ['read_mcp_resource', { server: 'docs', uri: 'docs://alpha' }],+ ] as const;+ const pm = h.registry.permissions;+ for (const context of [+ makeContext({ senderRole: 'member' }),+ makeContext({ channelType: 'internal', allowedTools: ['read_file'] }),+ makeContext({ allowedTools: [] }),+ ]) {+ await pm.withContext(context, async () => {+ for (const [name, args] of requests) {+ const result = await invoke(name, args);+ expect(result).toMatch(/unavailable to members|not allowed in this context/);+ expect(result).not.toContain('"docs"');+ }+ });+ }+ pm.setFailClosed(true);+ for (const [name, args] of requests) expect(await invoke(name, args)).toContain('fail-closed');+ pm.setFailClosed(false);+ expect(h.ask).not.toHaveBeenCalled();+ expect(h.calls().some((c) => c.method.startsWith('resources/'))).toBe(false);++ await pm.withContext(makeContext({ allowedTools: ['list_mcp_resources'] }), async () => {+ expect(await invoke('list_mcp_resources', {})).toBe('{"servers":["docs"]}');+ expect(await invoke('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' })).toContain('not allowed in this context');+ });+ await pm.withContext(makeContext({ allowedTools: ['read_mcp_resource'] }), async () => {+ expect(await invoke('list_mcp_resources', {})).toContain('not allowed in this context');+ expect(await invoke('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' })).toContain('Reference text');+ });+ expect(h.calls().filter((c) => c.method.startsWith('resources/'))).toHaveLength(1);+ expect(h.ask).not.toHaveBeenCalled();+ });++ it('remembers approval only for the same protocol, source channel, server and exact URI', async () => {+ const h = await harness({}, { answer: 'always' });+ const pm = h.registry.permissions;+ const read = (type: string, id: string, uri: string) => pm.withContext(makeContext({ channelType: type, channelId: id }), () => h.run('read_mcp_resource', { server: 'docs', uri }));+ await read('web', 'A', 'docs://alpha');+ await read('web', 'A', 'docs://alpha');+ expect(h.ask).toHaveBeenCalledTimes(1);+ await read('cli', 'A', 'docs://alpha');+ await read('web', 'B', 'docs://alpha');+ await read('web', 'A', 'docs://beta');+ await pm.withContext(makeContext({ channelType: 'web', channelId: 'A' }), () => h.run('list_mcp_resources', { server: 'docs' }));+ expect(h.ask).toHaveBeenCalledTimes(5);+ await pm.withContext(makeContext({ channelType: 'web', channelId: 'A' }), () => pm.checkMcpResource({ serverId: 'other', operation: 'read', uri: 'docs://alpha', autoApprove: false }));+ expect(h.ask).toHaveBeenCalledTimes(6);+ });++ it('asks through a real WebChannel even when Allow All is enabled', async () => {+ const h = await harness();+ const web = new WebChannel('Mercury');+ cleanups.push(() => web.stop());+ web.setBypassPermissions(true);+ web.addSSEClient({ enqueue() {}, close() {} } as unknown as ReadableStreamDefaultController, 'web-session');+ h.registry.permissions.setCurrentContext('web', 'web-session');+ h.registry.permissions.onAsk((prompt, options) => web.askPermission(prompt, 'web-session', options));+ const reading = h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' });+ const pending = web.pendingFor('web-session');+ expect(pending).toHaveLength(1);+ expect(h.calls().some((c) => c.method === 'resources/read')).toBe(false);+ expect(web.resolveApproval(pending[0].data!.id as string, 'no', 'web-session')).toBe(true);+ expect(await reading).toContain('denied');+ expect(h.calls().some((c) => c.method === 'resources/read')).toBe(false);+ });++ it('times out once without retrying a read', async () => {+ const h = await harness({ timeoutMs: 30 }, { answer: 'yes' });+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://slow' })).toMatch(/timed out/i);+ expect(h.calls().filter((c) => c.method === 'resources/read')).toHaveLength(1);+ });++ it('cancels a dispatched read without retrying and leaves the connection usable', async () => {+ const h = await harness({}, { answer: 'yes' });+ const ac = new AbortController();+ const reading = h.run('read_mcp_resource', { server: 'docs', uri: 'docs://slow' }, ac.signal);+ await vi.waitFor(() => expect(h.calls().filter((c) => c.method === 'resources/read')).toHaveLength(1));+ ac.abort();+ expect(await reading).toMatch(/cancel|abort/i);+ await vi.waitFor(() => expect(h.calls().some((c) => c.method === 'notifications/cancelled')).toBe(true));+ expect(h.calls().filter((c) => c.method === 'resources/read')).toHaveLength(1);+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' })).toContain('Reference text');+ });++ it('reconnects after a crash without replaying reads, and invalidates old catalog cursors', async () => {+ const h = await harness({}, { answer: 'always' });+ const first = JSON.parse(await h.run('list_mcp_resources', { server: 'docs' }));+ const oldPid = h.calls()[0].pid;+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://crash' })).toMatch(/closed|connection/i);+ await vi.waitFor(() => {+ expect(h.manager.status()[0].state).toBe('connected');+ expect(h.calls().some((c) => c.method === 'initialize' && c.pid !== oldPid)).toBe(true);+ }, { timeout: 5000 });+ expect(await h.run('list_mcp_resources', { server: 'docs', cursor: first.nextCursor })).toContain('cursor expired');+ expect(JSON.parse(await h.run('list_mcp_resources', { server: 'docs' })).resources[0].uri).toBe('docs://alpha');+ expect(h.calls().filter((c) => c.method === 'resources/read' && c.params?.uri === 'docs://crash')).toHaveLength(1);+ });++ it('uses the guarded HTTP transport and configured authentication for resource reads', async () => {+ const h = await harness({}, { answer: 'yes', http: true });+ expect(h.manager.status()[0].state).toBe('connected');+ expect(await h.run('read_mcp_resource', { server: 'docs', uri: 'docs://alpha' })).toContain('Reference text');+ expect(h.calls().filter((c) => c.method === 'resources/read')).toHaveLength(1);+ });+});++describe('resource configuration', () => {+ it('accepts URI filters while rejecting wildcard auto-approval and invalid URI fields', () => {+ const config = (resources: unknown) => validateMcpConfig({ servers: { docs: { transport: 'stdio', command: 'node', resources } } });+ expect(config({ allow: ['*'], deny: ['docs://private'], autoApprove: ['docs://alpha'] }).problems).toEqual([]);+ for (const resources of [{ autoApprove: ['*'] }, { allow: ['relative/path'] }, { allow: ['docs://newline\ninjection'] }, { allow: ['docs://' + 'x'.repeat(2048)] }]) {+ expect(config(resources).problems).toHaveLength(1);+ }+ expect(config({ allow: ['docs://alpha'], autoApprove: ['docs://beta'] }).warnings[0]).toContain('resources.allow');+ });+});diff --git a/src/capabilities/mcp/resources.ts b/src/capabilities/mcp/resources.tsnew file mode 100644index 00000000..916fcfc2--- /dev/null+++ b/src/capabilities/mcp/resources.ts@@ -0,0 +1,160 @@+import { randomUUID } from 'node:crypto';+import { tool, zodSchema, type Tool } from 'ai';+import { z } from 'zod';+import type { ListResourcesResult, ReadResourceResult } from '@modelcontextprotocol/client';+import { redactSecrets } from '../../utils/redact.js';+import { MAX_RESULT_CHARS } from './result.js';+import { isResourceUri, MAX_RESOURCE_URI_CHARS } from './resource-policy.js';+import { MCP_LIST_RESOURCES_TOOL, MCP_READ_RESOURCE_TOOL } from './naming.js';++export const MAX_CATALOG_PAGE_CHARS = 8 * 1024;+export const MAX_CATALOG_BUFFER_CHARS = 64 * 1024;+const MAX_CURSORS = 16;+const CURSOR_LIFETIME_MS = 5 * 60_000;++function clip(text: string, limit: number): string {+ const end = text.slice(0, limit);+ const last = end.charCodeAt(end.length - 1);+ return last >= 0xd800 && last <= 0xdbff ? end.slice(0, -1) : end;+}++interface ResourceSummary {+ uri: string;+ name: string;+ description?: string;+ mimeType?: string;+}++interface CatalogContinuation {+ serverId: string;+ generation: number;+ expiresAt: number;+ resources: ResourceSummary[];+ remoteCursor?: string;+ truncated: boolean;+}++/** Bounded metadata only. Resource contents are never retained here. */+export class ResourceCatalog {+ private readonly cursors = new Map<string, CatalogContinuation>();++ clear(serverId?: string): void {+ for (const [id, cursor] of this.cursors) {+ if (!serverId || cursor.serverId === serverId) this.cursors.delete(id);+ }+ }++ continuation(serverId: string, generation: number, cursor: string): CatalogContinuation {+ const saved = this.cursors.get(cursor);+ if (!saved || saved.serverId !== serverId || saved.generation !== generation || saved.expiresAt <= Date.now()) {+ throw new Error('Resource cursor expired or belongs to another server; list again without a cursor');+ }+ return saved;+ }++ prepare(serverId: string, generation: number, page: ListResourcesResult, allowed: (uri: string) => boolean): CatalogContinuation {+ const resources: ResourceSummary[] = [];+ let size = 0;+ let truncated = false;+ // Bound retained metadata even if a server ignores reasonable page sizes.+ for (const entry of page.resources.slice(0, 4096)) {+ if (!allowed(entry.uri) || redactSecrets(entry.uri) !== entry.uri) continue;+ const item: ResourceSummary = {+ uri: entry.uri,+ name: clip(redactSecrets(entry.name), 128),+ description: entry.description ? clip(redactSecrets(entry.description), 256) : undefined,+ mimeType: entry.mimeType ? clip(redactSecrets(entry.mimeType), 128) : undefined,+ };+ size += JSON.stringify(item).length;+ if (resources.length >= 256 || size > MAX_CATALOG_BUFFER_CHARS) { truncated = true; break; }+ resources.push(item);+ }+ if (page.resources.length > 4096) truncated = true;+ const remoteCursor = page.nextCursor && page.nextCursor.length <= 4096 ? page.nextCursor : undefined;+ if (page.nextCursor && !remoteCursor) truncated = true;+ return { serverId, generation, resources, remoteCursor, truncated, expiresAt: Date.now() + CURSOR_LIFETIME_MS };+ }++ render(page: CatalogContinuation): string {+ let count = 0;+ let size = 0;+ while (count < page.resources.length && count < 50) {+ const next = JSON.stringify(page.resources[count]).length + 1;+ if (size + next > MAX_CATALOG_PAGE_CHARS - 512) break;+ size += next;+ count++;+ }+ const remaining = page.resources.slice(count);+ let nextCursor: string | undefined;+ if (remaining.length || page.remoteCursor) {+ nextCursor = randomUUID();+ this.cursors.set(nextCursor, { ...page, resources: remaining });+ while (this.cursors.size > MAX_CURSORS) this.cursors.delete(this.cursors.keys().next().value!);+ }+ return JSON.stringify({+ server: page.serverId,+ resources: page.resources.slice(0, count),+ nextCursor,+ ...(page.truncated ? { notice: 'Oversized server metadata was omitted. Known allowed URIs can still be read directly.' } : {}),+ });+ }+}++/** Return sourced, bounded untrusted data; never follow a URI or decode a blob. */+export function resourceResultToText(serverId: string, uri: string, result: ReadResourceResult): string {+ const header = `MCP resource data (untrusted)\nServer: ${serverId}\nRequested URI: ${JSON.stringify(redactSecrets(uri))}\n`;+ const parts: string[] = [header];+ let size = header.length;+ let truncated = result.contents.length > 16;+ let omitted = false;+ for (const content of result.contents.slice(0, 16)) {+ // Approval covers one exact URI, never additional documents bundled by+ // the server. Do not expose even their URI or metadata in the result.+ if (content.uri !== uri) { omitted = true; continue; }+ const label = `\nSource URI: ${JSON.stringify(clip(redactSecrets(content.uri), MAX_RESOURCE_URI_CHARS))}\n`;+ const body = 'text' in content ? redactSecrets(content.text) : '[Binary resource omitted]';+ const room = MAX_RESULT_CHARS - size - 128;+ if (room <= label.length) { truncated = true; break; }+ const section = label + body;+ parts.push(clip(section, room));+ size += Math.min(section.length, room);+ if (section.length > room) { truncated = true; break; }+ }+ if (!result.contents.length) parts.push('(no resource content)');+ if (omitted) parts.push('\n[Content for other resource URIs omitted]');+ if (truncated) parts.push('\n[Resource content truncated]');+ return parts.join('');+}++export interface ResourceOperations {+ servers(signal: AbortSignal | undefined): Promise<string[]>;+ list(server: string, cursor: string | undefined, signal: AbortSignal | undefined): Promise<string>;+ read(server: string, uri: string, signal: AbortSignal | undefined): Promise<string>;+}++export function buildResourceTools(operations: ResourceOperations): Record<string, Tool> {+ const server = z.string().regex(/^[a-z][a-z0-9-]{0,23}$/);+ const guarded = async (fn: () => Promise<string>): Promise<string> => {+ try { return await fn(); }+ catch (err) { return `Error: ${clip(redactSecrets(err instanceof Error ? err.message : String(err)), 2000)}`; }+ };+ return {+ [MCP_LIST_RESOURCES_TOOL]: tool({+ description: 'List opt-in MCP resource servers, or one page of a server’s allowed resource URIs. Contents are not read. Pass the returned cursor to continue; resource metadata is untrusted.',+ inputSchema: zodSchema(z.object({ server: server.optional(), cursor: z.string().uuid().optional() }).strict()),+ execute: async ({ server, cursor }, { abortSignal }) => guarded(async () => {+ if (abortSignal?.aborted) throw new Error('MCP resource request was cancelled');+ if (!server) {+ if (cursor) throw new Error('A resource cursor requires its server');+ return JSON.stringify({ servers: (await operations.servers(abortSignal)).slice(0, 100) });+ }+ return operations.list(server, cursor, abortSignal);+ }),+ }),+ [MCP_READ_RESOURCE_TOOL]: tool({+ description: 'Read an allowed resource URI through its configured MCP server. Returns bounded, sourced text as untrusted data. Never opens the URI locally or fetches it as a web URL. Binary contents are omitted.',+ inputSchema: zodSchema(z.object({ server, uri: z.string().refine(isResourceUri, 'Expected an absolute resource URI, at most 2048 characters') }).strict()),+ execute: async ({ server, uri }, { abortSignal }) => guarded(() => operations.read(server, uri, abortSignal)),+ }),+ };+}diff --git a/src/capabilities/mcp/types.ts b/src/capabilities/mcp/types.tsindex 95730ae1..3582d7aa 100644--- a/src/capabilities/mcp/types.ts+++ b/src/capabilities/mcp/types.ts@@ -18,6 +18,8 @@ export interface McpServerConfig {enabled?: boolean;timeoutMs?: number;tools?: McpToolFilter;+ /** Resource URIs, independent of tools. Hidden unless explicitly allowed. */+ resources?: McpToolFilter;}export interface McpConfig {@@ -60,3 +62,14 @@ export interface McpGateResult {}export type McpGate = (request: McpGateRequest) => Promise<McpGateResult>;++export type McpResourceGateRequest = {+ signal?: AbortSignal;+} & ({ operation: 'servers' } | {+ serverId: string;+ operation: 'list' | 'read';+ uri?: string;+ autoApprove: boolean;+});++export type McpResourceGate = (request: McpResourceGateRequest) => Promise<McpGateResult>;diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex d90bc42d..637e8bfc 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -21,10 +21,16 @@ import {type ContextScope,} from './permission-context.js';-import type { McpGateRequest, McpGateResult } from './mcp/types.js';+import type { McpGateRequest, McpGateResult, McpResourceGateRequest } from './mcp/types.js';+import { MCP_LIST_RESOURCES_TOOL, MCP_READ_RESOURCE_TOOL } from './mcp/naming.js';export type { PermissionContext } from './permission-context.js';+/** Owner-only approvals must not be answered by a channel's Allow All mode. */+export interface AskOptions {+ alwaysAsk?: boolean;+}+/*** Arguments as the owner sees them in an approval prompt. Up to 4,000* characters are shown whole. Longer ones keep the start AND the end, with@@ -389,7 +395,8 @@ export function splitShellSegments(command: string): string[] {export class PermissionManager {private manifest: PermissionsManifest;private readonly cwd: string;- private askHandler?: (prompt: string) => Promise<string>;+ private askHandler?: (prompt: string, options?: AskOptions) => Promise<string>;+ private approvedMcpResourcesByContext = new Map<string, Set<string>>();private turnAnswers: Array<{ action: string; answer: 'yes' | 'no' | 'always' }> = [];/*** The main agent's (root) context: replaced, never mutated, by the@@ -567,11 +574,11 @@ export class PermissionManager {return this.ctx().senderRole;}- onAsk(handler: (prompt: string) => Promise<string>): void {+ onAsk(handler: (prompt: string, options?: AskOptions) => Promise<string>): void {// Every answer the owner gives is evidence for the Owner Model (autonomy,// risk per action type); the learning loop drains it once per turn.- this.askHandler = async (prompt: string) => {- const answer = await handler(prompt);+ this.askHandler = async (prompt: string, options?: AskOptions) => {+ const answer = await (options ? handler(prompt, options) : handler(prompt));if (answer === 'yes' || answer === 'no' || answer === 'always') {const action = prompt.split('\n')[0].replace(/:.*$/, '').trim().slice(0, 40) || 'action';this.turnAnswers.push({ action, answer });@@ -1138,6 +1145,46 @@ export class PermissionManager {return { allowed: false, reason: `User denied MCP tool ${label}` };}+ async checkMcpResource(request: McpResourceGateRequest): Promise<McpGateResult> {+ const { operation, signal } = request;+ if (signal?.aborted) return { allowed: false, reason: 'MCP resource request was cancelled' };+ const ctx = this.ctx();+ if (ctx.senderRole === 'member' || this.failClosed) {+ return { allowed: false, reason: 'MCP resources are unavailable to members and fail-closed agents' };+ }+ const toolName = operation === 'read' ? MCP_READ_RESOURCE_TOOL : MCP_LIST_RESOURCES_TOOL;+ if (ctx.allowedTools && !ctx.allowedTools.includes(toolName)) {+ return { allowed: false, reason: `MCP resource helper ${toolName} is not allowed in this context` };+ }+ // Local server enumeration needs no owner prompt, but retained helpers+ // must still respect the current caller's role and exact tool allowlist.+ if (operation === 'servers') return { allowed: true };+ const { serverId, uri } = request;+ if (operation === 'read' && uri && request.autoApprove) return { allowed: true };+ // Resource grants never collide with tool grants, other protocols, or+ // another URI on the same server. The caller's scoped source channel is+ // used, so concurrent turns retain their own approval identity.+ const channel = JSON.stringify([ctx.channelType, ctx.channelId]);+ const key = JSON.stringify([serverId, operation, operation === 'read' ? uri : null]);+ if (this.approvedMcpResourcesByContext.get(channel)?.has(key)) return { allowed: true };+ if (!this.askHandler || ctx.channelType === 'internal') {+ return { allowed: false, reason: 'MCP resources need owner approval; unattended reads require the exact URI in resources.autoApprove' };+ }+ const answer = await this.askHandler(+ `MCP resource ${operation}\nServer: ${serverId}${operation === 'read' ? `\nURI: ${JSON.stringify(redactSecrets(uri ?? ''))}` : '\nList the allowed resource names and URIs (contents are not read).'}`,+ { alwaysAsk: true },+ );+ if (signal?.aborted) return { allowed: false, reason: 'MCP resource request was cancelled' };+ if (answer === 'always') {+ const approved = this.approvedMcpResourcesByContext.get(channel) ?? new Set<string>();+ approved.add(key);+ this.approvedMcpResourcesByContext.set(channel, approved);+ }+ return answer === 'yes' || answer === 'always'+ ? { allowed: true }+ : { allowed: false, reason: `User denied MCP resource ${operation} on ${serverId}` };+ }+private isProtectedConfigPath(path: string): boolean {const caseInsensitive = process.platform === 'win32' || process.platform === 'darwin';const normalize = (p: string) => (caseInsensitive ? p.toLowerCase() : p);diff --git a/src/channels/web.ts b/src/channels/web.tsindex ee5dc535..f3cb2f52 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -418,8 +418,8 @@ export class WebChannel extends BaseChannel {this.broadcast({ type: 'thinking', data: { targetId: _targetId } });}- async askPermission(prompt: string, _targetId?: string): Promise<string> {- if (this.isPermissionBypassed(_targetId)) return 'yes';+ async askPermission(prompt: string, _targetId?: string, options?: { alwaysAsk?: boolean }): Promise<string> {+ if (!options?.alwaysAsk && this.isPermissionBypassed(_targetId)) return 'yes';if (!this.hasInteractiveTarget(_targetId)) return 'no';const id = `perm_${randomUUID()}`;const event: ChatEvent = {diff --git a/src/index.ts b/src/index.tsindex 639aef08..c1217ff7 100644--- a/src/index.ts+++ b/src/index.ts@@ -2721,6 +2721,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {// terminal attached to a live daemon must not start every stdio server twice.const mcpManager = daemonOwnsRuntime ? undefined : new McpManager(mcpConfig.servers, {gate: (request) => capabilities.permissions.checkMcpTool(request),+ resourceGate: (request) => capabilities.permissions.checkMcpResource(request),});if (mcpManager) {capabilities.attachMcp(mcpManager);@@ -3772,7 +3773,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {setWebSpotify(spotifyClient);}- capabilities.permissions.onAsk(async (prompt: string) => {+ capabilities.permissions.onAsk(async (prompt: string, options) => {const channelType = capabilities.permissions.getCurrentChannelType();const { channelId } = capabilities.getChannelContext();if (channelType === 'telegram' && tgChannel) {@@ -3782,7 +3783,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {return (channels.get('signal') as SignalChannel).askPermission(prompt, channelId);}if (channelType === 'web' && webChannel) {- return webChannel.askPermission(prompt, channelId);+ return webChannel.askPermission(prompt, channelId, options);}// Any other channel that can ask (plugin channels such as WhatsApp).const asking = channels.get(channelType as Parameters<typeof channels.get>[0]) as { askPermission?: (p: string, id?: string) => Promise<string> } | undefined;diff --git a/src/utils/tool-label.ts b/src/utils/tool-label.tsindex f885162c..1350e01f 100644--- a/src/utils/tool-label.ts+++ b/src/utils/tool-label.ts@@ -8,6 +8,8 @@ const TOOL_LABELS: Record<string, { icon: string; label: string; argKey?: stringedit_file: { icon: '✂️', label: 'Editing', argKey: 'path', argTransform: basename },delete_file: { icon: '🗑', label: 'Deleting', argKey: 'path', argTransform: basename },list_dir: { icon: '📂', label: 'Listing', argKey: 'path', argTransform: basename },+ list_mcp_resources: { icon: '🔌', label: 'Listing MCP resources', argKey: 'server' },+ read_mcp_resource: { icon: '🔌', label: 'Reading MCP resource', argKey: 'uri', argTransform: truncate(60) },approve_scope: { icon: '🔓', label: 'Approving scope' },run_command: { icon: '⌨', label: 'Running command', argKey: 'command', argTransform: truncate(40) },cd: { icon: '📂', label: 'Changing dir to', argKey: 'path' },@@ -238,4 +240,4 @@ export function formatNarrative(}return lines.join('\n');-}\ No newline at end of file+}diff --git a/website/docs/integrations/mcp.mdx b/website/docs/integrations/mcp.mdxindex efe0e504..c231d9af 100644--- a/website/docs/integrations/mcp.mdx+++ b/website/docs/integrations/mcp.mdx@@ -9,7 +9,7 @@ You stay in control. A server's tools are hidden until you allow them, every cal:::info[What is supported]-MCP **tools** over **stdio** (a local command Mercury starts) and **Streamable HTTP** (a remote URL), with static headers for authentication. MCP resources, prompts, sampling, OAuth sign-in and legacy SSE servers are not supported yet. Mercury Bots do not get MCP tools.+MCP **tools** and opt-in **text resources** over **stdio** (a local command Mercury starts) and **Streamable HTTP** (a remote URL), with static headers for authentication. Resource templates and subscriptions, prompts, sampling, OAuth sign-in and legacy SSE servers are not supported yet. Mercury Bots do not get MCP tools or resources.:::@@ -138,9 +138,44 @@ mcp:| `tools.allow` | both | Tool names the agent may see; `"*"` means all. **Default: none.** || `tools.deny` | both | Tool names that are always hidden; wins over `allow` || `tools.autoApprove` | both | Exact tool names that run without asking (no wildcards) |+| `resources.allow` | both | Resource URIs the agent may list and read; `"*"` allows all. **Default: none.** Independent of `tools.allow`. |+| `resources.deny` | both | Resource URIs that stay hidden and cannot be read; wins over `allow` |+| `resources.autoApprove` | both | Exact allowed URIs that may be read without asking, including unattended. No wildcards. |An invalid server entry is skipped with a warning in the log and in `mercury doctor --mcp`; the rest still load. A missing `${env:NAME}` variable marks that server as failed with `env NAME is not set`.+## Reading resource context++Some servers expose documents, database schemas or reference material as MCP resources. Enable the URIs you want in that server's configuration, then restart Mercury:++```yaml+mcp:+ servers:+ docs:+ transport: http+ url: https://mcp.example.com/mcp+ headers:+ Authorization: "Bearer ${env:DOCS_MCP_TOKEN}"+ resources:+ allow: ["docs://handbook", "docs://database-schema"]+ autoApprove: ["docs://database-schema"]+```++`mercury mcp list` displays these filters. Existing tool allowlists never enable resources. A server that exposes only resources is supported too.++Ask Mercury to consult the handbook or schema. Two tools become available when a connected server supports resources and has an explicit resource allowlist:++- `list_mcp_resources` lists enabled resource servers without a network request. With `server`, it asks before listing one page of allowed resource metadata. Pass the returned `cursor` with the same server to continue. Listing does not read contents.+- `read_mcp_resource` reads an exact `server` and `uri` through that server, including a resource link returned by one of its tools. The URI is never opened as a local file or fetched as an ordinary web URL. Results identify their server and source URI; text is untrusted data and cannot grant permissions.++Resource approvals are separate from tool approvals. **Allow All still asks**, including in the web dashboard and attached terminal. **Always** on a read remembers only that server and exact URI in the current source chat; it never approves a different document or the catalog. Listing has its own approval. Unattended runs cannot list; they can only read exact allowed URIs named in `resources.autoApprove`. Bots, non-admin channel members and plan mode do not receive resource tools.++Reads return at most 32,768 characters. Binary contents are omitted, registered secrets are redacted, and oversized text is marked as truncated. Catalog responses are capped at 8,192 characters and 50 entries; larger server pages continue through bounded metadata buffers. If a server exceeds those buffers, Mercury reports omitted metadata rather than silently claiming the catalog is complete. A known allowed URI can still be read directly. Cursors expire after five minutes or a reconnect.++Read responses include only content whose returned source URI exactly matches the requested URI. Extra documents are omitted even if their URIs are otherwise allowed; they need their own read request and approval. Source URIs are server assertions: Mercury cannot verify whether an untrusted server mislabeled the bytes it returned. Retained resource helpers recheck the current caller's role and exact tool allowlist, including when listing server IDs locally.++Catalog pagination is explicit: the SDK is not allowed to fetch every remote page automatically. Read results bypass its content cache. Requests use the server's existing timeout and cancellation signal. Disconnects reconnect the server without replaying the interrupted request. These caps limit retained catalog data and model context; the MCP SDK still parses the server's incoming response before Mercury formats it.+## How Mercury runs servers- **When.** Enabled servers connect in the background when Mercury starts. A slow or broken server never delays startup or blocks other tools. Servers reconnect with backoff (1s doubling to 5 minutes, up to 10 attempts) if a connection drops.