feat(ai-secure-mcp): self-hostable secure MCP server on an extracted ai-isolate base #2157
- @@ -58,4 +58,4 @@5858 "quickjs-emscripten": "^0.31.0"5959 },6060 "peerDependencies": {61- "@tanstack/ai-code-mode": "workspace:^"61+ "@tanstack/ai-isolate": "workspace:^"
jherr changed the title
- @@ -0,0 +67,21 @@67+ egress: ['https://api.hue.local'], // deny-by-default allowlist68+ policy: {69+ scopes: { setLights: 'control' }, // setLights needs the control scope70+ approve: ['buyMovie'], // buyMovie needs two-phase approval71+ },72+ audit: { path: './audit.jsonl', retentionDays: 90 },73+ notify: ntfyNotifier({ topic: 'my-home-mcp' }),74+ funnel: { port: 8787 },75+})76+77+// Serve it from your HTTP handler.78+export default server.fetch79+```80+81+`server.preflight` holds the secure-default problems. `server.tailscale` holds82+the command to expose the server when you pass `funnel`.83+84+## Reaching the network from a tool85+86+A tool receives the `egress` capability on `ctx.context`. It is the only way to87+the network, and it refuses any origin not on the allowlist.@@ -0,0 +35,21 @@35+ pendingCount: () => number36+}37+38+export function createApprovalStore(options?: {39+ /** How long a proposal stays valid, 300000 ms (5 minutes) by default. */40+ ttlMs?: number41+ /** A clock in ms, for tests. */42+ now?: () => number43+ /** An id source, for tests. */44+ newId?: () => string45+}): ApprovalStore {46+ const ttlMs = options?.ttlMs ?? 300_00047+ const now = options?.now ?? (() => Date.now())48+ const newId = options?.newId ?? (() => randomUUID())49+ const proposals = new Map<string, Proposal>()50+51+ return {52+ propose: ({ owner, summary, run }) => {53+ const proposalId = newId()54+ const expiresAt = now() + ttlMs55+ proposals.set(proposalId, { owner, summary, run, expiresAt })@@ -0,0 +20,21 @@20+/**21+ * Keeps only id-like and query-like fields; everything else is redacted. The22+ * match is a suffix, so camelCase (`movieId`) and snake_case (`movie_id`) both23+ * count.24+ */25+const KEEP = /(id|ids|query|q|name|title|kind|type|scope|origin)$/i26+27+/**28+ * Redacts tool input to id-like and query-like fields. A non-object becomes a29+ * type tag. This keeps a useful trail without storing a secret value.30+ */31+export function redactArgs(args: unknown): unknown {32+ if (args === null || typeof args !== 'object') {33+ return args === undefined ? undefined : `[${typeof args}]`34+ }35+ if (Array.isArray(args)) return '[array]'36+ const out: Record<string, unknown> = {}37+ for (const [key, value] of Object.entries(args as Record<string, unknown>)) {38+ out[key] =39+ KEEP.test(key) && (typeof value === 'string' || typeof value === 'number')40+ ? value@@ -0,0 +45,21 @@45+46+export interface AuditLog {47+ record: (entry: AuditEntry) => Promise<void>48+}49+50+/**51+ * An append-only JSONL audit log. Each line is one event with a timestamp and52+ * redacted args. On start it drops lines older than `retentionDays`.53+ *54+ * @param options.path - The JSONL file to append to55+ * @param options.retentionDays - Days to keep; older lines are pruned on start56+ * @param options.now - A clock in ms, for tests57+ */58+export function createAuditLog(options: {59+ path: string60+ retentionDays?: number61+ now?: () => number62+}): AuditLog {63+ const now = options.now ?? (() => Date.now())64+ // Prune and ensure the directory on first write, once.65+ const ready = (async () => {@@ -0,0 +8,21 @@8+ * presented token.9+ */10+export function hashToken(token: string): string {11+ return createHash('sha256').update(token, 'utf8').digest('hex')12+}13+14+/**15+ * Compares two hex strings in constant time. Returns false for a length16+ * mismatch. Use it so a timing side channel cannot reveal the token.17+ */18+export function constantTimeEqual(a: string, b: string): boolean {19+ const left = Buffer.from(a, 'utf8')20+ const right = Buffer.from(b, 'utf8')21+ if (left.length !== right.length) return false22+ return timingSafeEqual(left, right)23+}24+25+/** Reads the bearer token from an `Authorization` header value. */26+export function bearerToken(header: string | null): string | undefined {27+ if (header === null) return undefined28+ const match = /^Bearer (.+)$/.exec(header.trim())@@ -0,0 +6,21 @@6+ return typeof value === 'object' && value !== null7+}8+9+function toClient(value: unknown, index: number): ClientRecord {10+ if (11+ !isRecord(value) ||12+ typeof value.id !== 'string' ||13+ typeof value.tokenHash !== 'string' ||14+ !Array.isArray(value.scopes)15+ ) {16+ throw new SecureMcpError(17+ 'invalid_input',18+ `Client at index ${index} needs id, tokenHash, and scopes.`,19+ )20+ }21+ const client: ClientRecord = {22+ id: value.id,23+ tokenHash: value.tokenHash,24+ scopes: value.scopes.filter((s): s is string => typeof s === 'string'),25+ }26+ if (Array.isArray(value.targets)) {@@ -0,0 +11,21 @@11+ !isRecord(value) ||12+ typeof value.id !== 'string' ||13+ typeof value.tokenHash !== 'string' ||14+ !Array.isArray(value.scopes)15+ ) {16+ throw new SecureMcpError(17+ 'invalid_input',18+ `Client at index ${index} needs id, tokenHash, and scopes.`,19+ )20+ }21+ const client: ClientRecord = {22+ id: value.id,23+ tokenHash: value.tokenHash,24+ scopes: value.scopes.filter((s): s is string => typeof s === 'string'),25+ }26+ if (Array.isArray(value.targets)) {27+ client.targets = value.targets.filter(28+ (t): t is string => typeof t === 'string',29+ )30+ }31+ if (typeof value.expiresAt === 'number') {@@ -0,0 +45,21 @@45+ return async (url, init) => {46+ let origin: string47+ try {48+ origin = new URL(url).origin49+ } catch {50+ throw new SecureMcpError('invalid_input', `Not a URL: ${url}`)51+ }52+ if (!allowed.has(origin)) {53+ options.onDenied?.(origin)54+ throw new SecureMcpError(55+ 'egress_denied',56+ `Egress to ${origin} is not on the allowlist.`,57+ )58+ }59+ const controller = new AbortController()60+ const timer = setTimeout(() => controller.abort(), timeoutMs)61+ try {62+ return await fetchImpl(url, {63+ ...init,64+ redirect: 'error',65+ signal: controller.signal,@@ -0,0 +54,21 @@54+ throw new SecureMcpError(55+ 'egress_denied',56+ `Egress to ${origin} is not on the allowlist.`,57+ )58+ }59+ const controller = new AbortController()60+ const timer = setTimeout(() => controller.abort(), timeoutMs)61+ try {62+ return await fetchImpl(url, {63+ ...init,64+ redirect: 'error',65+ signal: controller.signal,66+ })67+ } catch (error) {68+ const detail = error instanceof Error ? error.message : 'request failed'69+ throw new SecureMcpError(70+ 'backend_unavailable',71+ `Egress to ${origin} failed: ${detail}`,72+ )73+ } finally {74+ clearTimeout(timer)@@ -0,0 +59,21 @@59+ const client = readClient(context)60+61+ const scope = deps.policy.scopes?.[tool.name]62+ if (scope !== undefined && !client.scopes.includes(scope)) {63+ return refuse(deps, client, tool.name, args, 'forbidden_scope', `This token does not hold the "${scope}" scope.`)64+ }65+66+ const targetField = deps.policy.targetParam?.[tool.name]67+ if (targetField !== undefined && client.targets !== undefined) {68+ const value = isRecord(args) ? args[targetField] : undefined69+ if (!client.targets.includes(String(value))) {70+ return refuse(deps, client, tool.name, args, 'forbidden_scope', 'This token may not reach that target.')71+ }72+ }73+74+ if (deps.policy.approve?.includes(tool.name)) {75+ const summary = deps.summarize(tool.name, args)76+ const envelope = deps.approvals.propose({77+ owner: client.id,78+ summary,79+ run: async () => original?.(args, context),@@ -0,0 +90,21 @@90+ let egressTimeoutMs: number | undefined91+ if (config.egress !== undefined) {92+ if ('allow' in config.egress) {93+ allow = config.egress.allow94+ egressTimeoutMs = config.egress.timeoutMs95+ } else {96+ allow = config.egress97+ }98+ }99+ const egress = createEgress({100+ allow,101+ ...(egressTimeoutMs === undefined ? {} : { timeoutMs: egressTimeoutMs }),102+ onDenied: (origin) => void notify.notify({ kind: 'egress_denied', origin }),103+ })104+105+ const policy: AccessPolicy = config.policy ?? {}106+ const approvals = createApprovalStore(config.approval)107+ const summarize =108+ config.summarize ?? ((toolName: string) => `Run ${toolName}`)109+110+ const guarded = guardTools(config.tools, {@@ -0,0 +131,21 @@131+ : createRateLimiter(config.rateLimit ?? { limit: 60, windowMs: 60_000 })132+133+ const check = preflight({134+ clients: config.clients,135+ egressDenyByDefault: allow.length > 0,136+ auditOn: audit !== undefined,137+ notifierOn: config.notify !== undefined,138+ })139+ if (config.funnel?.public === true && !check.ok) {140+ throw new SecureMcpError(141+ 'invalid_input',142+ `Refusing to expose a public funnel. Fix: ${check.problems.join(' ')}`,143+ )144+ }145+146+ const nowSeconds = () => Math.floor(Date.now() / 1000)147+148+ const fetch = async (request: Request): Promise<Response> => {149+ const token = bearerToken(request.headers.get('authorization'))150+ if (token === undefined) {151+ void notify.notify({ kind: 'auth_failure' })@@ -0,0 +167,21 @@167+ if (rl !== undefined && !rl.allow(client.id)) {168+ void notify.notify({ kind: 'rate_limited', client: client.id })169+ await audit?.record({170+ client: client.id,171+ event: 'rate_limited',172+ outcome: 'denied',173+ })174+ return jsonError(429, 'rate_limited')175+ }176+177+ const authInfo: AuthInfo = {178+ token: '[redacted]',179+ clientId: client.id,180+ scopes: client.scopes,181+ expiresAt: client.expiresAt ?? FAR_FUTURE,182+ extra: {},183+ }184+185+ return inner.handle(request, {186+ authInfo,187+ context: { secure: { client }, egress },
github-actions[bot](GitHub profile, opens in a new tab) assignedtombeckenham
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
Applied a fix from CIb5e6378
tanstack-source reviewed
@@ -0,0 +73,21 @@73+74+ if (deps.policy.approve?.includes(tool.name)) {75+ const summary = deps.summarize(tool.name, args)76+ const envelope = deps.approvals.propose({77+ owner: client.id,78+ summary,79+ run: async () => original?.(args, context),80+ })81+ await deps.audit?.record({82+ client: client.id,83+ event: 'tool_proposed',84+ tool: tool.name,85+ outcome: 'ok',86+ args,87+ })88+ void deps.notify.notify({89+ kind: 'approval_pending',90+ proposalId: envelope.proposalId,91+ summary,92+ })93+ return envelope@@ -0,0 +6,21 @@6+ return typeof value === 'object' && value !== null7+}8+9+function toClient(value: unknown, index: number): ClientRecord {10+ if (11+ !isRecord(value) ||12+ typeof value.id !== 'string' ||13+ typeof value.tokenHash !== 'string' ||14+ !Array.isArray(value.scopes)15+ ) {16+ throw new SecureMcpError(17+ 'invalid_input',18+ `Client at index ${index} needs id, tokenHash, and scopes.`,19+ )20+ }21+ const client: ClientRecord = {22+ id: value.id,23+ tokenHash: value.tokenHash,24+ scopes: value.scopes.filter((s): s is string => typeof s === 'string'),25+ }26+ if (Array.isArray(value.targets)) {@@ -0,0 +11,21 @@11+ !isRecord(value) ||12+ typeof value.id !== 'string' ||13+ typeof value.tokenHash !== 'string' ||14+ !Array.isArray(value.scopes)15+ ) {16+ throw new SecureMcpError(17+ 'invalid_input',18+ `Client at index ${index} needs id, tokenHash, and scopes.`,19+ )20+ }21+ const client: ClientRecord = {22+ id: value.id,23+ tokenHash: value.tokenHash,24+ scopes: value.scopes.filter((s): s is string => typeof s === 'string'),25+ }26+ if (Array.isArray(value.targets)) {27+ client.targets = value.targets.filter(28+ (t): t is string => typeof t === 'string',29+ )30+ }31+ if (typeof value.expiresAt === 'number') {@@ -0,0 +5,21 @@5+export interface AuditEntry {6+ /** The client id, or undefined for an unauthenticated attempt. */7+ client?: string8+ /** What happened, for example `tool_call`, `auth_failure`, `egress_denied`. */9+ event: string10+ /** The tool name, when the event is a tool call. */11+ tool?: string12+ /** `ok`, `denied`, or `error`. */13+ outcome: string14+ /** The raw tool input. It is redacted before it is written. */15+ args?: unknown16+ /** The error code, when the outcome is an error. */17+ code?: string18+}19+20+/**21+ * Keeps only id-like and query-like fields; everything else is redacted. The22+ * match is a suffix, so camelCase (`movieId`) and snake_case (`movie_id`) both23+ * count.24+ */25+const KEEP = /(id|ids|query|q|name|title|kind|type|scope|origin)$/i@@ -0,0 +35,21 @@35+ pendingCount: () => number36+}37+38+export function createApprovalStore(options?: {39+ /** How long a proposal stays valid, 300000 ms (5 minutes) by default. */40+ ttlMs?: number41+ /** A clock in ms, for tests. */42+ now?: () => number43+ /** An id source, for tests. */44+ newId?: () => string45+}): ApprovalStore {46+ const ttlMs = options?.ttlMs ?? 300_00047+ const now = options?.now ?? (() => Date.now())48+ const newId = options?.newId ?? (() => randomUUID())49+ const proposals = new Map<string, Proposal>()50+51+ return {52+ propose: ({ owner, summary, run }) => {53+ const proposalId = newId()54+ const expiresAt = now() + ttlMs55+ proposals.set(proposalId, { owner, summary, run, expiresAt })@@ -0,0 +131,21 @@131+ : createRateLimiter(config.rateLimit ?? { limit: 60, windowMs: 60_000 })132+133+ const check = preflight({134+ clients: config.clients,135+ egressDenyByDefault: allow.length > 0,136+ auditOn: audit !== undefined,137+ notifierOn: config.notify !== undefined,138+ })139+ if (config.funnel?.public === true && !check.ok) {140+ throw new SecureMcpError(141+ 'invalid_input',142+ `Refusing to expose a public funnel. Fix: ${check.problems.join(' ')}`,143+ )144+ }145+146+ const nowSeconds = () => Math.floor(Date.now() / 1000)147+148+ const fetch = async (request: Request): Promise<Response> => {149+ const token = bearerToken(request.headers.get('authorization'))150+ if (token === undefined) {151+ void notify.notify({ kind: 'auth_failure' })@@ -0,0 +45,21 @@45+46+export interface AuditLog {47+ record: (entry: AuditEntry) => Promise<void>48+}49+50+/**51+ * An append-only JSONL audit log. Each line is one event with a timestamp and52+ * redacted args. On start it drops lines older than `retentionDays`.53+ *54+ * @param options.path - The JSONL file to append to55+ * @param options.retentionDays - Days to keep; older lines are pruned on start56+ * @param options.now - A clock in ms, for tests57+ */58+export function createAuditLog(options: {59+ path: string60+ retentionDays?: number61+ now?: () => number62+}): AuditLog {63+ const now = options.now ?? (() => Date.now())64+ // Prune and ensure the directory on first write, once.65+ const ready = (async () => {@@ -0,0 +45,21 @@45+ return async (url, init) => {46+ let origin: string47+ try {48+ origin = new URL(url).origin49+ } catch {50+ throw new SecureMcpError('invalid_input', `Not a URL: ${url}`)51+ }52+ if (!allowed.has(origin)) {53+ options.onDenied?.(origin)54+ throw new SecureMcpError(55+ 'egress_denied',56+ `Egress to ${origin} is not on the allowlist.`,57+ )58+ }59+ const controller = new AbortController()60+ const timer = setTimeout(() => controller.abort(), timeoutMs)61+ try {62+ return await fetchImpl(url, {63+ ...init,64+ redirect: 'error',65+ signal: controller.signal,@@ -0,0 +139,21 @@139+ throw new SecureMcpError(code, message)140+}141+142+/**143+ * Builds the `approve_proposal` tool. A client confirms its own pending144+ * proposal by id; the stored action then runs host-side.145+ */146+export function createConfirmTool(deps: {147+ approvals: ApprovalStore148+ audit?: AuditLog149+}): AnyServerTool {150+ const tool: AnyServerTool = toolDefinition({151+ name: 'approve_proposal',152+ description:153+ 'Confirm a pending approval by its proposalId. Runs the proposed action.',154+ inputSchema: z.object({155+ proposalId: z.string().describe('The id from an approval_required reply.'),156+ }),157+ }).server<SecureRequestContext>(async ({ proposalId }, context) => {158+ const client = readClient(context)159+ const result = await deps.approvals.confirm(proposalId, client.id)@@ -0,0 +82,21 @@82+): SecureMcpServer {83+ const notify = config.notify ?? silentNotifier()84+ const audit: AuditLog | undefined =85+ config.audit === false || config.audit === undefined86+ ? undefined87+ : createAuditLog(config.audit)88+89+ let allow: ReadonlyArray<string> = []90+ let egressTimeoutMs: number | undefined91+ if (config.egress !== undefined) {92+ if ('allow' in config.egress) {93+ allow = config.egress.allow94+ egressTimeoutMs = config.egress.timeoutMs95+ } else {96+ allow = config.egress97+ }98+ }99+ const egress = createEgress({100+ allow,101+ ...(egressTimeoutMs === undefined ? {} : { timeoutMs: egressTimeoutMs }),102+ onDenied: (origin) => void notify.notify({ kind: 'egress_denied', origin }),@@ -0,0 +66,21 @@66+ ],67+ egress: ['https://api.hue.local'], // deny-by-default allowlist68+ policy: {69+ scopes: { setLights: 'control' }, // setLights needs the control scope70+ approve: ['buyMovie'], // buyMovie needs two-phase approval71+ },72+ audit: { path: './audit.jsonl', retentionDays: 90 },73+ notify: ntfyNotifier({ topic: 'my-home-mcp' }),74+ funnel: { port: 8787 },75+})76+77+// Serve it from your HTTP handler.78+export default server.fetch79+```80+81+`server.preflight` holds the secure-default problems. `server.tailscale` holds82+the command to expose the server when you pass `funnel`.83+84+## Reaching the network from a tool85+86+A tool receives the `egress` capability on `ctx.context`. It is the only way togithub-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
Pushed79ef312
- @@ -27,4 +27,4 @@2727 ## Installation28282929 ```bash30-pnpm add @tanstack/ai-isolate-e2b @tanstack/ai-code-mode e2b30+pnpm add @tanstack/ai-isolate-e2b @tanstack/ai-isolate e2b@@ -0,0 +12,21 @@12+ src="https://tanstack.com/api/readme/ai.png"13+ alt="TanStack AI"14+ width="900"15+ />16+ </picture>17+</div>18+19+<br />20+21+# @tanstack/ai-secure-mcp22+23+A security envelope around [`createMCPServer`](https://www.npmjs.com/package/@tanstack/ai-mcp)24+for a self-hoster who wants to expose a TanStack AI MCP server to the internet.25+26+It wraps your server with:27+28+**Hashed-token auth** — bearer tokens stored as SHA-256 hashes, constant-time compare.29+**Scopes and a target allowlist** — a token holds scopes; a scope can be narrowed to named resources.30+**Deny-by-default egress helper** — one allowlisted `egress` capability a tool uses on purpose. It is not an enforced network boundary: a tool that calls global `fetch` still reaches the network. For enforced isolation, run the server behind a separate execution or network boundary.31+**Rate limits** — a per-client sliding window.32+**A redacted audit log** — append-only JSONL, args redacted to id-like fields, no secrets.@@ -0,0 +99,21 @@99+ name: 'getLights',100+ description: 'List the lights on the Hue bridge',101+ inputSchema: z.object({}),102+}).server<SecureRequestContext>(async (_args, ctx) => {103+ const res = await ctx.context.egress('https://api.hue.local/lights')104+ return { status: res.status }105+})106+```107+108+## Two-phase approval109+110+A tool in `policy.approve` does not act on the first call. It returns an111+envelope:112+113+```json114+{ "status": "approval_required", "proposalId": "…", "summary": "Run buyMovie" }115+```116+117+A separate, authenticated call to the `approve_proposal` tool with that118+`proposalId` runs the action. Proposals are in memory, single-use, and expire,119+so a crash cannot leave a ghost approval.@@ -0,0 +110,21 @@110+A tool in `policy.approve` does not act on the first call. It returns an111+envelope:112+113+```json114+{ "status": "approval_required", "proposalId": "…", "summary": "Run buyMovie" }115+```116+117+A separate, authenticated call to the `approve_proposal` tool with that118+`proposalId` runs the action. Proposals are in memory, single-use, and expire,119+so a crash cannot leave a ghost approval.120+121+## Secure defaults122+123+| Concern | Default | Footgun it prevents |124+| -------------- | ------------------------------------------------ | ------------------------------------------------------------------------------ |125+| Egress helper | deny-by-default allowlist | a tool exfiltrating data _when it uses `ctx.context.egress`_ |126+| Generic HTTP | not injected into the context | SSRF through a "helpful" tool _that reaches the network only through `egress`_ |127+| Tokens | hash-only, constant-time | replay from a leaked store |128+| Secrets | never in the audit log or a notification | prompt/response exfiltration |129+| Approval state | in memory, fail-closed on restart | a ghost approval after a crash |130+| Exposure | tailnet-only unless you opt into a public funnel | accidental internet |@@ -0,0 +51,21 @@51+ record: (entry: AuditEntry) => Promise<void>52+}53+54+/**55+ * An append-only JSONL audit log. Each line is one event with a timestamp and56+ * redacted args. On start it drops lines older than `retentionDays`.57+ *58+ * @param options.path - The JSONL file to append to59+ * @param options.retentionDays - Days to keep; older lines are pruned on start60+ * @param options.now - A clock in ms, for tests61+ */62+export function createAuditLog(options: {63+ path: string64+ retentionDays?: number65+ now?: () => number66+}): AuditLog {67+ const now = options.now ?? (() => Date.now())68+ const init = async () => {69+ await mkdir(dirname(options.path), { recursive: true }).catch(() => {})70+ if (options.retentionDays === undefined) return71+ const cutoff = now() - options.retentionDays * 86_400_000@@ -0,0 +42,21 @@42+ const fetchImpl = options.fetch ?? fetch43+44+ return async (url, init) => {45+ let origin: string46+ try {47+ origin = new URL(url).origin48+ } catch {49+ throw new SecureMcpError('invalid_input', `Not a URL: ${url}`)50+ }51+ if (!allowed.has(origin)) {52+ options.onDenied?.(origin)53+ throw new SecureMcpError(54+ 'egress_denied',55+ `Egress to ${origin} is not on the allowlist.`,56+ )57+ }58+ const controller = new AbortController()59+ // The deadline stays armed until the caller's combined signal settles, so it60+ // still aborts a slow body stream: `fetch` resolves on headers, not on body61+ // completion. The timer fires at most once and is cleared on cancellation.62+ const timer = setTimeout(() => controller.abort(), timeoutMs)@@ -0,0 +59,21 @@59+ // The deadline stays armed until the caller's combined signal settles, so it60+ // still aborts a slow body stream: `fetch` resolves on headers, not on body61+ // completion. The timer fires at most once and is cleared on cancellation.62+ const timer = setTimeout(() => controller.abort(), timeoutMs)63+ // Combine the caller's signal with the timeout so caller cancellation still64+ // aborts the request and an already-aborted caller signal is honored,65+ // instead of replacing `init.signal` with a fresh active one.66+ const signal = combineSignals(init?.signal ?? undefined, controller.signal)67+ // Clear the timer once the operation can no longer time out: either the68+ // deadline fired, or the caller aborted, or the caller finished reading and69+ // dropped its reference (GC'd timer). Attach cleanup to the combined signal.70+ if (signal.aborted) {71+ clearTimeout(timer)72+ throw new SecureMcpError(73+ 'backend_unavailable',74+ `Egress to ${origin} failed: ${signal.reason instanceof Error ? signal.reason.message : 'aborted'}`,75+ )76+ }77+ signal.addEventListener('abort', () => clearTimeout(timer), { once: true })78+ try {79+ return await fetchImpl(url, {@@ -0,0 +84,21 @@84+ } catch (error) {85+ clearTimeout(timer)86+ const detail = error instanceof Error ? error.message : 'request failed'87+ throw new SecureMcpError(88+ 'backend_unavailable',89+ `Egress to ${origin} failed: ${detail}`,90+ )91+ }92+ }93+}94+95+/** Combines abort signals; aborts the result when any input aborts. */96+function combineSignals(97+ a: AbortSignal | undefined,98+ b: AbortSignal,99+): AbortSignal {100+ if (a === undefined) return b101+ // `AbortSignal.any` is available on every runtime this package targets102+ // (Node 18.17+, modern browsers). It aborts as soon as either input aborts103+ // and carries the first abort reason.104+ return AbortSignal.any([a, b])
Pushed2cb0c53
- @@ -0,0 +106,21 @@106+```107+108+## Two-phase approval109+110+A tool in `policy.approve` does not act on the first call. It returns an111+envelope:112+113+```json114+{ "status": "approval_required", "proposalId": "…", "summary": "Run buyMovie" }115+```116+117+A separate, authenticated call to the `approve_proposal` tool with that118+`proposalId` runs the action. Proposals are in memory, single-use, and expire,119+so a crash cannot leave a ghost approval.120+121+The confirm step checks only that the confirming client id matches the client122+that made the proposal. It is not an independent approver: the same client, with123+the same token, can make both the proposal and the confirm. This two-phase flow124+adds a deliberate second step and an audit trail; it does not by itself prove a125+human reviewed the action. For real human-in-the-loop approval, route the126+confirm through a different client or an out-of-band channel.@@ -0,0 +63,21 @@63+ // the event loop open on its own, so a completed request can let the process64+ // exit without waiting out the remaining `timeoutMs`.65+ const timer = setTimeout(() => controller.abort(), timeoutMs)66+ timer.unref?.()67+ // Combine the caller's signal with the timeout so caller cancellation still68+ // aborts the request and an already-aborted caller signal is honored,69+ // instead of replacing `init.signal` with a fresh active one.70+ const signal = combineSignals(init?.signal ?? undefined, controller.signal)71+ // Clear the timer once the operation can no longer time out: either the72+ // deadline fired, or the caller aborted, or the caller finished reading and73+ // dropped its reference (GC'd timer). Attach cleanup to the combined signal.74+ if (signal.aborted) {75+ clearTimeout(timer)76+ throw new SecureMcpError(77+ 'backend_unavailable',78+ `Egress to ${origin} failed: ${signal.reason instanceof Error ? signal.reason.message : 'aborted'}`,79+ )80+ }81+ signal.addEventListener('abort', () => clearTimeout(timer), { once: true })82+ const fail = (error: unknown): SecureMcpError => {83+ clearTimeout(timer)@@ -0,0 +142,21 @@142+}143+144+/** Combines abort signals; aborts the result when any input aborts. */145+function combineSignals(146+ a: AbortSignal | undefined,147+ b: AbortSignal,148+): AbortSignal {149+ if (a === undefined) return b150+ // `AbortSignal.any` is the fast path, but `engines.node` allows 18.16 where151+ // it does not exist yet (added in 18.17). The lib types assume it is always152+ // present, so guard with a runtime check and fall back to a manual combiner153+ // so a caller signal on an older runtime does not throw before fetch runs.154+ if (typeof AbortSignal.any === 'function') return AbortSignal.any([a, b])155+ const controller = new AbortController()156+ const abort = (reason: unknown) => controller.abort(reason)157+ for (const s of [a, b]) {158+ if (s.aborted) {159+ abort(s.reason)160+ break161+ }162+ s.addEventListener('abort', () => abort(s.reason), { once: true })@@ -0,0 +72,21 @@72+ const controller = new AbortController()73+ await egress('https://api.hue.local/x', { signal: controller.signal })74+ expect(seen).toBeInstanceOf(AbortSignal)75+ expect(seen?.aborted).toBe(false)76+ // A later caller abort propagates to the signal fetch received.77+ controller.abort()78+ expect(seen?.aborted).toBe(true)79+ })80+81+ it('unrefs the deadline timer so a completed request does not hold the loop', async () => {82+ let timer: { unref?: () => void } | undefined83+ const spy = vi.spyOn(global, 'setTimeout')84+ const egress = createEgress({85+ allow: ['https://api.hue.local'],86+ fetch: async () => new Response('body'),87+ })88+ await egress('https://api.hue.local/x')89+ timer = spy.mock.results[0]?.value90+ // Node timers expose `unref`; it must have been called so a finished91+ // request cannot delay process exit by the remaining timeout.92+ expect(typeof timer?.unref).toBe('function')
Pushed9ace518
tombeckenham approved these changes
tombeckenham turned on merge when ready (squash)
tanstack-source turned off merge when readybecause the branch has conflicts with its base branch
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
tanstack-source reviewed
@@ -0,0 +119,21 @@119+120+ const ids = new Set<string>()121+ for (const client of config.clients) {122+ // Two records with one id share a rate-limit bucket and can confirm each123+ // other's proposals.124+ if (ids.has(client.id)) {125+ throw new SecureMcpError(126+ 'invalid_input',127+ `Client id "${client.id}" is used more than once.`,128+ )129+ }130+ ids.add(client.id)131+ // `expiresAt` is Unix seconds. A value from `Date.now()` is milliseconds132+ // and would expire in about 50,000 years.133+ if (client.expiresAt !== undefined && client.expiresAt > MAX_EXPIRES_AT) {134+ throw new SecureMcpError(135+ 'invalid_input',136+ `Client "${client.id}" has an expiresAt in milliseconds. Use Unix seconds.`,137+ )138+ }139+ }@@ -0,0 +97,21 @@97+ // unhandled rejection on any of the fire-and-forget (`void`) call sites.98+ const notify = safeNotifier(config.notify ?? silentNotifier())99+ const audit: AuditLog | undefined =100+ config.audit === false || config.audit === undefined101+ ? undefined102+ : createAuditLog(config.audit)103+104+ let allow: ReadonlyArray<string> = []105+ let egressTimeoutMs: number | undefined106+ if (config.egress !== undefined) {107+ if ('allow' in config.egress) {108+ allow = config.egress.allow109+ egressTimeoutMs = config.egress.timeoutMs110+ } else {111+ allow = config.egress112+ }113+ }114+ const egress = createEgress({115+ allow,116+ ...(egressTimeoutMs === undefined ? {} : { timeoutMs: egressTimeoutMs }),117+ onDenied: (origin) => void notify.notify({ kind: 'egress_denied', origin }),@@ -0,0 +135,21 @@135+ 'invalid_input',136+ `Client "${client.id}" has an expiresAt in milliseconds. Use Unix seconds.`,137+ )138+ }139+ }140+141+ const policy: AccessPolicy = config.policy ?? {}142+ const approvals = createApprovalStore<GuardContext>(config.approval)143+ const summarize =144+ config.summarize ?? ((toolName: string) => `Run ${toolName}`)145+146+ const guarded = guardTools(config.tools, {147+ policy,148+ approvals,149+ audit,150+ notify,151+ summarize,152+ })153+ const tools: Array<AnyServerTool> = policy.approve?.length154+ ? [...guarded, createConfirmTool({ approvals, audit })]155+ : guarded
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
Walkthrough
The pull request adds
@tanstack/ai-isolateas the shared home for isolate contracts andwrapCode, then updates Code Mode and six drivers to use or re-export it. It also adds@tanstack/ai-secure-mcp, with authentication, tool access controls, approvals, audit logging, notifications, rate limiting, and deployment checks.Changes: Isolate Contract Extraction
packages/ai-isolate/*,.changeset/extract-ai-isolate-contract.mdwrapCodeexport. Adds package configuration and README documentation.packages/ai-code-mode/package.json,packages/ai-code-mode/src/index.ts,packages/ai-code-mode/src/types.tswrapCodeand isolate types from@tanstack/ai-isolate.packages/ai-isolate-cloudflare/*,packages/ai-isolate-daytona/*,packages/ai-isolate-e2b/*,packages/ai-isolate-node/*,packages/ai-isolate-quickjs-bun/*,packages/ai-isolate-quickjs/*@tanstack/ai-isolate.Secure MCP Server
packages/ai-secure-mcp/src/types.ts,packages/ai-secure-mcp/src/index.ts,packages/ai-secure-mcp/package.json,packages/ai-secure-mcp/tsconfig.json,packages/ai-secure-mcp/vite.config.ts,packages/ai-secure-mcp/README.md,.changeset/add-ai-secure-mcp.mdpackages/ai-secure-mcp/src/auth.ts,packages/ai-secure-mcp/src/clients-file.ts,packages/ai-secure-mcp/src/egress.ts,packages/ai-secure-mcp/src/rate-limit.ts,packages/ai-secure-mcp/src/guard.ts,packages/ai-secure-mcp/tests/*packages/ai-secure-mcp/src/approval.ts,packages/ai-secure-mcp/src/audit.ts,packages/ai-secure-mcp/src/notifier.ts,packages/ai-secure-mcp/tests/approval.test.ts,packages/ai-secure-mcp/tests/audit.test.ts,packages/ai-secure-mcp/tests/notifier.test.tspackages/ai-secure-mcp/src/server.ts,packages/ai-secure-mcp/src/deploy.ts,packages/ai-secure-mcp/tests/server.test.ts,packages/ai-secure-mcp/tests/deploy.test.tsEstimated code review effort: 4 (Complex) | ~50 minutes
Change: Feature
Sequence Diagram(s)#
Suggested reviewers:
alemtuzlakMerge Risk:
Moderate · previous review
2cb0cThe package adds a security-focused MCP server with several unresolved hardening and documentation gaps, mainly around egress enforcement, audit and notification handling, and example configuration. These should be addressed or explicitly accepted before merge. Rollback is a simple revert.
Pre-merge checks:
4
@tanstack/ai-secure-mcp), and mentions the extractedai-isolatebase, which the PR also adds. It follows the convent…Full details: Title check
Explanation
The title names the main change, a new self-hostable secure MCP server package (
@tanstack/ai-secure-mcp), and mentions the extractedai-isolatebase, which the PR also adds. It follows the conventional commit style and is one line of plain text. The title covers the main change without listing files.Full details: Description check
Explanation
The description follows the repository template. It has the Changes section, the checklist, and the Release Impact section. It also adds a Testing section, a Risk and rollback section, and a Public API change section. The Changes section explains the new
@tanstack/ai-secure-mcppackage and the extraction of@tanstack/ai-isolate, and it lists review fixes. The checklist leaves the docs item unchecked and the author states that no docs/ page was added, so the docs gap is disclosed. The description does not say whether the docs item is intentionally deferred beyond the note in the Testing section, and it leaves the 'not docs/CI/dev-only' release box unchecked while checking the changeset box. These are minor inconsistencies. The required sections and key information are present, so the check passes.Finishing Touches
Generate unit tests (beta)
Fix failing CI checks
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Share