Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
/**
* T1 fixtures — remote MCP-OAuth discovery (spec 19 §7 T1).
*
* These are the EXACT bytes returned by the real production servers on 2026-09-20
* (curl, `Accept: application/json`), copied verbatim from the live probe. They are
* NOT hand-authored — a PRM/AS shape the real server cannot emit would leave the
* discovery code unreachable. Each entry cites its probe URL. Parsing the raw string
* (mirroring `Response.json()`) is what the discovery client consumes.
*
* Probe method — the discovery client probes the MCP URL with GET; re-sondeo
* 2026-09-20 confirmed the four pilots emit the same `WWW-Authenticate:
* resource_metadata` challenge on GET as on POST (all pointing at the
* path-suffixed well-known), so the GET probe is derived from the real producer,
* not invented. Real GET responses (2026-09-20):
* GET https://mcp.notion.com/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.notion.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", …
* GET https://mcp.linear.app/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.linear.app/.well-known/oauth-protected-resource/mcp", error="invalid_token", …
* GET https://mcp.sentry.dev/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp"
* GET https://mcp.canva.com/mcp → 401 www-authenticate: Bearer realm="OAuth", resource_metadata="https://mcp.canva.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", …
* (POST initialize returns the identical header on all four.)
*
* Transport probe (sondeo POST en vivo 2026-09-25): the tokenless `POST initialize` of
* the four CIMD pilots returns 401 with the same Bearer challenge (transport alive,
* token required); Vercel's `/mcp` returns 404 (dead) while `/` returns 200
* `text/event-stream`. Those bytes back the `VERCEL_PILOT` + the `initialize` table
* below — derived from the real producer, not hand-invented.
*
* Provenance: scratchpad/c1-fixtures-provenance.md (sondeo en vivo 2026-09-20,
* sección "EVIDENCIA GET") + the 2026-09-25 POST probe.
*/
import type { DbClient } from '../../src/db.js'
import type { PinnedTransport } from '../../src/http/pinnedFetch.js'
// ─── Notion (resource base sin path) ────────────────────────────────────────
// PRM: GET https://mcp.notion.com/.well-known/oauth-protected-resource → 200
export const NOTION_PRM_JSON =
'{"resource":"https://mcp.notion.com","authorization_servers":["https://mcp.notion.com"],"scopes_supported":["default"],"bearer_methods_supported":["header"],"resource_name":"Notion MCP (Beta)"}'
// AS: GET https://mcp.notion.com/.well-known/oauth-authorization-server → 200
export const NOTION_AS_JSON =
'{"issuer":"https://mcp.notion.com","authorization_endpoint":"https://mcp.notion.com/authorize","token_endpoint":"https://mcp.notion.com/token","registration_endpoint":"https://mcp.notion.com/register","scopes_supported":["default"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.notion.com/token","code_challenge_methods_supported":["plain","S256"],"client_id_metadata_document_supported":true,"introspection_endpoint":"https://mcp.notion.com/introspect","introspection_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"]}'
// ─── Linear (resource con path /mcp; PRM en root Y path-suffixed) ───────────
// PRM (root): GET https://mcp.linear.app/.well-known/oauth-protected-resource → 200
export const LINEAR_PRM_JSON =
'{"resource":"https://mcp.linear.app/mcp","authorization_servers":["https://mcp.linear.app"],"scopes_supported":["read","write"],"bearer_methods_supported":["header"]}'
// AS: GET https://mcp.linear.app/.well-known/oauth-authorization-server → 200
// Re-probed 2026-09-29: Linear now advertises RFC 9207
// (`authorization_response_iss_parameter_supported: true`), which the 2026-09-20 bytes
// did not carry. Byte-identical otherwise.
export const LINEAR_AS_JSON =
'{"issuer":"https://mcp.linear.app","authorization_endpoint":"https://mcp.linear.app/authorize","token_endpoint":"https://mcp.linear.app/token","registration_endpoint":"https://mcp.linear.app/register","scopes_supported":["read","write","openid","email"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.linear.app/token","code_challenge_methods_supported":["S256"],"authorization_response_iss_parameter_supported":true,"client_id_metadata_document_supported":true,"resource":"https://mcp.linear.app/mcp","resource_metadata":"https://mcp.linear.app/.well-known/oauth-protected-resource/mcp"}'
// ─── Sentry (PRM SOLO path-suffixed; root → 404; 401 trae WWW-Authenticate) ─
// 401 header emitted identically on GET and POST of https://mcp.sentry.dev/mcp
// (the client probes with GET; POST initialize returns the same header).
export const SENTRY_WWW_AUTHENTICATE =
'Bearer realm="OAuth", resource_metadata="https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp"'
// PRM: GET https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp → 200
export const SENTRY_PRM_JSON =
'{"resource":"https://mcp.sentry.dev/mcp","authorization_servers":["https://mcp.sentry.dev"],"scopes_supported":["org:read","project:write","team:write","event:write"],"bearer_methods_supported":["header"]}'
// AS: GET https://mcp.sentry.dev/.well-known/oauth-authorization-server → 200
export const SENTRY_AS_JSON =
'{"issuer":"https://mcp.sentry.dev","authorization_endpoint":"https://mcp.sentry.dev/oauth/authorize","token_endpoint":"https://mcp.sentry.dev/oauth/token","registration_endpoint":"https://mcp.sentry.dev/oauth/register","scopes_supported":["org:read","project:write","team:write","event:write"],"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.sentry.dev/oauth/token","code_challenge_methods_supported":["S256"],"authorization_response_iss_parameter_supported":true,"client_id_metadata_document_supported":true}'
// ─── Canva (resource base sin path) ─────────────────────────────────────────
// PRM: GET https://mcp.canva.com/.well-known/oauth-protected-resource → 200
export const CANVA_PRM_JSON =
'{"resource":"https://mcp.canva.com","authorization_servers":["https://mcp.canva.com"],"scopes_supported":["profile:read","design:meta:read","design:content:write","design:content:read","folder:read","folder:write","brandtemplate:content:read","brandtemplate:meta:read","brandtemplate:content:write","comment:write","comment:read","asset:read","asset:write","brandkit:read","help:answers:read","help:answers:write"],"bearer_methods_supported":["header"]}'
// AS: GET https://mcp.canva.com/.well-known/oauth-authorization-server → 200
export const CANVA_AS_JSON =
'{"issuer":"https://mcp.canva.com","authorization_endpoint":"https://mcp.canva.com/authorize","token_endpoint":"https://mcp.canva.com/token","registration_endpoint":"https://mcp.canva.com/register","response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:jwt-bearer"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"revocation_endpoint":"https://mcp.canva.com/token","code_challenge_methods_supported":["plain","S256"],"client_id_metadata_document_supported":true,"authorization_grant_profiles_supported":["urn:ietf:params:oauth:grant-profile:id-jag"]}'
export interface PilotFixture {
name: string
/** MCP server URL discovery is entered with. */
mcpUrl: string
prm: { url: string; json: string }
/**
* The ROOT PRM (`/.well-known/oauth-protected-resource`, no path suffix) when the
* server serves a distinct one — the source of the transport probe's canonical-URL
* suggestion (Vercel: root PRM `resource` is `https://mcp.vercel.com/`).
*/
prmRoot?: { url: string; json: string }
/** Additional well-known/PRM URLs the server 404s on (for candidate fallback). */
prmNotFound?: string[]
/** WWW-Authenticate header the 401 probe of `mcpUrl` returns, if any. */
wwwAuthenticate?: string
/**
* Per-URL response of the tokenless `POST initialize` transport probe, keyed by the
* exact URL POSTed (the typed MCP URL and any canonical candidate). Vercel: `/mcp` →
* 404, `/` → 200 event-stream. The 4 CIMD pilots omit this — the transport defaults
* their POST to the real 401 challenge (transport alive, token required).
*/
initialize?: Record<string, { status: number; headers: Record<string, string> }>
as: { url: string; json: string }
/**
* Further authorization-server metadata URLs the AS serves, each with its real status
* (Entra: the multi-tenant `organizations` authority → 200, an unknown tenant → 400).
*/
asExtra?: Array<{ url: string; status: number; json: string }>
}
/** The 4 CIMD-ready pilots, keyed by the real well-known URLs they serve. */
export const PILOTS: Record<'notion' | 'linear' | 'sentry' | 'canva', PilotFixture> = {
notion: {
name: 'notion',
mcpUrl: 'https://mcp.notion.com/mcp',
// Notion serves PRM only at root; the path-suffixed candidate 404s.
prm: {
url: 'https://mcp.notion.com/.well-known/oauth-protected-resource',
json: NOTION_PRM_JSON,
},
prmNotFound: ['https://mcp.notion.com/.well-known/oauth-protected-resource/mcp'],
as: {
url: 'https://mcp.notion.com/.well-known/oauth-authorization-server',
json: NOTION_AS_JSON,
},
},
linear: {
name: 'linear',
mcpUrl: 'https://mcp.linear.app/mcp',
prm: {
url: 'https://mcp.linear.app/.well-known/oauth-protected-resource/mcp',
json: LINEAR_PRM_JSON,
},
as: {
url: 'https://mcp.linear.app/.well-known/oauth-authorization-server',
json: LINEAR_AS_JSON,
},
},
sentry: {
name: 'sentry',
mcpUrl: 'https://mcp.sentry.dev/mcp',
wwwAuthenticate: SENTRY_WWW_AUTHENTICATE,
prm: {
url: 'https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp',
json: SENTRY_PRM_JSON,
},
// Sentry root well-known 404s — only the path-suffixed form (or the hint) works.
prmNotFound: ['https://mcp.sentry.dev/.well-known/oauth-protected-resource'],
as: {
url: 'https://mcp.sentry.dev/.well-known/oauth-authorization-server',
json: SENTRY_AS_JSON,
},
},
canva: {
name: 'canva',
mcpUrl: 'https://mcp.canva.com/mcp',
prm: {
url: 'https://mcp.canva.com/.well-known/oauth-protected-resource',
json: CANVA_PRM_JSON,
},
prmNotFound: ['https://mcp.canva.com/.well-known/oauth-protected-resource/mcp'],
as: {
url: 'https://mcp.canva.com/.well-known/oauth-authorization-server',
json: CANVA_AS_JSON,
},
},
}
// ─── Vercel (DCR, NOT CIMD) — transport probe repro (sondeo en vivo 2026-09-25) ──
//
// The exact bytes Vercel returned on 2026-09-25. Vercel serves OAuth metadata
// PER-PATH (both root and `/mcp` PRM answer 200) but its MCP transport lives at the
// ROOT `/`: POST `initialize` to `/mcp` → 404 (Next.js 404 page), to `/` → 200
// `text/event-stream`. This is the exact URL-resolution gap the probe closes. Vercel's
// AS omits `none` from `token_endpoint_auth_methods_supported` → mode `dcr`.
//
// PROVENANCE (curl, 2026-09-25):
// GET https://mcp.vercel.com/.well-known/oauth-protected-resource → 200 (root, resource `/`)
// GET https://mcp.vercel.com/.well-known/oauth-protected-resource/mcp → 200 (path, resource `/mcp`)
// GET https://vercel.com/.well-known/oauth-authorization-server → 200
// POST initialize https://mcp.vercel.com/mcp → 404 text/html; https://mcp.vercel.com/ → 200 text/event-stream
/** Root PRM: resource is the canonical root `https://mcp.vercel.com/`. */
export const VERCEL_PRM_ROOT_JSON =
'{"resource":"https://mcp.vercel.com/","authorization_servers":["https://vercel.com"],"scopes_supported":["openid"],"resource_name":"Vercel MCP","resource_documentation":"https://vercel.com/docs/mcp/vercel-mcp","organization_name":"Vercel","organization_uri":"https://vercel.com","description":"Vercel\'s official MCP server — Vercel platform tools, deployment management, and documentation for AI assistants.","logo_uri":"https://mcp.vercel.com/icons/vercel-light.svg"}'
/** Path-suffixed PRM: resource echoes the typed `/mcp` path (what fooled Detect). */
export const VERCEL_PRM_MCP_JSON =
'{"resource":"https://mcp.vercel.com/mcp","authorization_servers":["https://vercel.com"],"scopes_supported":["openid"],"resource_name":"Vercel MCP","resource_documentation":"https://vercel.com/docs/mcp/vercel-mcp","organization_name":"Vercel","organization_uri":"https://vercel.com","description":"Vercel\'s official MCP server — Vercel platform tools, deployment management, and documentation for AI assistants.","logo_uri":"https://mcp.vercel.com/icons/vercel-light.svg"}'
export const VERCEL_AS_JSON =
'{"issuer":"https://vercel.com","jwks_uri":"https://vercel.com/.well-known/jwks","subject_types_supported":["public"],"response_types_supported":["code"],"response_modes_supported":["web_message.opener"],"claims_supported":["sub","aud","exp","iat","iss","jti","nbf","nonce","preferred_username","email","picture"],"id_token_signing_alg_values_supported":["RS256"],"scopes_supported":["openid","email","profile","offline_access"],"authorization_endpoint":"https://vercel.com/oauth/authorize","device_authorization_endpoint":"https://api.vercel.com/login/oauth/device-authorization","token_endpoint":"https://api.vercel.com/login/oauth/token","revocation_endpoint":"https://api.vercel.com/login/oauth/token/revoke","userinfo_endpoint":"https://api.vercel.com/login/oauth/userinfo","code_challenge_methods_supported":["S256"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","client_secret_jwt","private_key_jwt"],"grant_types_supported":["authorization_code","client_credentials","refresh_token","urn:ietf:params:oauth:grant-type:device_code"],"registration_endpoint":"https://api.vercel.com/login/oauth/register"}'
/**
* Vercel pilot — DCR (not CIMD), kept OUT of the `PILOTS` record so the CIMD discovery
* loop (`oauth.discovery.test.ts`) is untouched. Discovery resolves through the
* path-suffixed PRM (`resource: …/mcp`), while the transport probe finds `/mcp` dead
* (404) and suggests the root `/` from the root PRM's `resource`.
*/
export const VERCEL_PILOT: PilotFixture = {
name: 'vercel',
mcpUrl: 'https://mcp.vercel.com/mcp',
prm: {
url: 'https://mcp.vercel.com/.well-known/oauth-protected-resource/mcp',
json: VERCEL_PRM_MCP_JSON,
},
prmRoot: {
url: 'https://mcp.vercel.com/.well-known/oauth-protected-resource',
json: VERCEL_PRM_ROOT_JSON,
},
as: {
url: 'https://vercel.com/.well-known/oauth-authorization-server',
json: VERCEL_AS_JSON,
},
initialize: {
'https://mcp.vercel.com/mcp': {
status: 404,
headers: { 'content-type': 'text/html; charset=utf-8' },
},
'https://mcp.vercel.com/': { status: 200, headers: { 'content-type': 'text/event-stream' } },
},
}
// ─── Atlassian v2 + Dropbox — ASes WITHOUT RFC 9207 (sondeo en vivo 2026-09-29) ──
//
// The exact bytes both servers returned on 2026-09-29 (curl, `Accept: application/json`).
// Neither AS advertises `authorization_response_iss_parameter_supported`, so both take
// the per-server callback path and the same-site rule applies to their endpoints.
//
// PROVENANCE (curl, 2026-09-29):
// GET https://mcp.atlassian.com/v2/mcp → 401 www-authenticate: Bearer resource_metadata="https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp"
// GET https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp → 200
// GET https://auth.atlassian.com/.well-known/oauth-authorization-server/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3 → 200
// GET https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/.well-known/openid-configuration → 404
// GET https://mcp.dropbox.com/mcp → 401 www-authenticate: Bearer resource_metadata="https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", error_description="missing bearer token"
// GET https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp → 200
// GET https://www.dropbox.com/.well-known/oauth-authorization-server → 200
//
// Atlassian: CIMD + DCR + `none`, every endpoint on atlassian.com (same site as the
// issuer) → DCR, never CIMD. Dropbox: token and revocation endpoints on
// api.dropboxapi.com while the issuer is www.dropbox.com → cross-site.
export const ATLASSIAN_V2_WWW_AUTHENTICATE =
'Bearer resource_metadata="https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp"'
export const ATLASSIAN_V2_PRM_JSON =
'{"resource":"https://mcp.atlassian.com/v2/mcp","authorization_servers":["https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3"],"bearer_methods_supported":["header"],"scopes_supported":["read:me","read:account","offline_access","email","read:jira:agent-interface","write:jira:agent-interface","search:jira:agent-interface","delete:jira:agent-interface","manage:jira:agent-interface","read:confluence:agent-interface","write:confluence:agent-interface","search:confluence:agent-interface","search:rovo:agent-interface","search:code:agent-interface","read:all:twg","write:all:twg","read:goals:agent-interface","write:goals:agent-interface","read:projects:agent-interface","write:projects:agent-interface","read:bitbucket:agent-interface","write:bitbucket:agent-interface","read:loom:agent-interface","write:loom:agent-interface","read:talent:agent-interface","write:talent:agent-interface","read:jira-align:agent-interface","write:jira-align:agent-interface","read:teams:agent-interface","write:teams:agent-interface","read:artifacts:agent-interface","write:artifacts:agent-interface","read:capacity-planning:agent-interface","write:capacity-planning:agent-interface","read:focus:agent-interface","write:focus:agent-interface","read:assets:agent-interface","write:assets:agent-interface"],"resource_documentation":"https://www.atlassian.com/platform/remote-mcp-server"}'
export const ATLASSIAN_V2_AS_JSON =
'{"authorization_endpoint":"https://auth.atlassian.com/authorize","client_id_metadata_document_supported":true,"code_challenge_methods_supported":["S256"],"grant_types_supported":["authorization_code","client_credentials","refresh_token","urn:ietf:params:oauth:grant-type:token-revoke","urn:ietf:params:oauth:grant-type:jwt-bearer","urn:ietf:params:oauth:grant-type:token-exchange"],"issuer":"https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3","jwks_uri":"https://auth.atlassian.com/.well-known/jwks.json","pushed_authorization_request_endpoint":"https://auth.atlassian.com/oauth/par","registration_endpoint":"https://auth.atlassian.com/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3/dcr/register","response_types_supported":["code","token"],"revocation_endpoint":"https://auth.atlassian.com/oauth/revoke","token_endpoint":"https://auth.atlassian.com/oauth/token","token_endpoint_auth_methods_supported":["none","client_secret_post","client_secret_basic","private_key_jwt"]}'
export const ATLASSIAN_V2_PILOT: PilotFixture = {
name: 'atlassian-v2',
mcpUrl: 'https://mcp.atlassian.com/v2/mcp',
wwwAuthenticate: ATLASSIAN_V2_WWW_AUTHENTICATE,
prm: {
url: 'https://mcp.atlassian.com/.well-known/oauth-protected-resource/v2/mcp',
json: ATLASSIAN_V2_PRM_JSON,
},
as: {
url: 'https://auth.atlassian.com/.well-known/oauth-authorization-server/VCeDsk8ZHncYF1g234fKtc4lNipbBhu3',
json: ATLASSIAN_V2_AS_JSON,
},
}
export const DROPBOX_WWW_AUTHENTICATE =
'Bearer resource_metadata="https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp", error="invalid_token", error_description="missing bearer token"'
export const DROPBOX_PRM_JSON =
'{"resource":"https://mcp.dropbox.com/mcp","authorization_servers":["https://www.dropbox.com"],"scopes_supported":["account_info.read","file_requests.read","file_requests.write","files.content.read","files.content.write","files.metadata.read","files.metadata.write","sharing.read","sharing.write"]}'
export const DROPBOX_AS_JSON =
'{"issuer": "https://www.dropbox.com", "authorization_endpoint": "https://www.dropbox.com/oauth2/authorize", "token_endpoint": "https://api.dropboxapi.com/oauth2/token", "revocation_endpoint": "https://api.dropboxapi.com/2/auth/token/revoke", "scopes_supported": ["account_info.read", "contacts.read", "contacts.write", "files.metadata.read", "files.content.read", "files.content.write", "files.permanent_delete", "files.metadata.write", "sharing.read", "sharing.write", "file_requests.read", "file_requests.write", "openid", "profile", "email", "account_info.write", "backup.read", "backup.write", "dash/content.read", "dash/content.write", "team_info.read", "team_info.write", "sessions.list", "sessions.modify", "members.read", "members.write", "members.delete", "groups.read", "groups.write", "events.read", "team_data.governance.read", "team_data.governance.write", "team_data.member", "team_data.content.read", "team_data.content.write", "team_data.team_space", "files.team_metadata.write", "events.write", "files.team_metadata.read"], "response_types_supported": ["code"], "grant_types_supported": ["authorization_code", "client_credentials", "refresh_token", "device_code"], "code_challenge_methods_supported": ["plain", "S256"], "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic", "none"], "registration_endpoint": "https://www.dropbox.com/oauth2/register"}'
export const DROPBOX_PILOT: PilotFixture = {
name: 'dropbox',
mcpUrl: 'https://mcp.dropbox.com/mcp',
wwwAuthenticate: DROPBOX_WWW_AUTHENTICATE,
prm: {
url: 'https://mcp.dropbox.com/.well-known/oauth-protected-resource/mcp',
json: DROPBOX_PRM_JSON,
},
as: {
url: 'https://www.dropbox.com/.well-known/oauth-authorization-server',
json: DROPBOX_AS_JSON,
},
}
// ─── Microsoft Entra ID: Work IQ + Agent 365 (live probe 2026-10-21T14:16Z) ──
//
// The exact bytes these servers returned on 2026-10-21T14:16Z (tokenless GET, and
// POST initialize for the 401 challenge). The tenant 72f988bf-… is Microsoft's own
// public tenant; the tenant 00000000-…-000000000001 does not exist.
//
// PROVENANCE (curl, 2026-10-21T14:16Z):
// POST https://workiq.svc.cloud.microsoft/mcp (initialize) → 401 WWW-Authenticate below (same on GET)
// GET https://workiq.svc.cloud.microsoft/.well-known/oauth-protected-resource/mcp → 200
// POST https://agent365.svc.cloud.microsoft/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools → 401
// GET https://agent365.svc.cloud.microsoft/.well-known/oauth-protected-resource/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools → 200
// GET https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration → 200
// GET https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0/.well-known/openid-configuration → 200
// GET https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0/.well-known/openid-configuration → 400 invalid_tenant
// GET https://login.microsoftonline.com/.well-known/oauth-authorization-server/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0 → 404
//
// What these bytes show: Entra serves only OIDC discovery (RFC 8414 well-known → 404);
// the multi-tenant `organizations` authority declares the literal templated issuer
// `https://login.microsoftonline.com/{tenantid}/v2.0`, while a tenant authority
// declares its concrete issuer; and neither advertises code_challenge_methods_supported,
// grant_types_supported, RFC 9207 or a registration endpoint.
export const WORKIQ_WWW_AUTHENTICATE =
'Bearer realm="", authorization_uri="https://login.microsoftonline.com/common/oauth2/authorize", client_id="fdcc1f02-fc51-4226-8753-f668596af7f7", resource_metadata="https://workiq.svc.cloud.microsoft/.well-known/oauth-protected-resource/mcp"'
export const WORKIQ_PRM_JSON =
'{"resource":"https://workiq.svc.cloud.microsoft/mcp","authorization_servers":["https://login.microsoftonline.com/organizations/v2.0"],"scopes_supported":["fdcc1f02-fc51-4226-8753-f668596af7f7/WorkIQAgent.Ask"],"bearer_methods_supported":["header"],"resource_name":"Work IQ","openai_apps_challenge":"IK2HLqUDHBbQHQfkX-WkPX2CgUAlr7mbybpWV1zBXZ0"}'
export const AGENT365_MAIL_WWW_AUTHENTICATE =
'Bearer resource_metadata="https://agent365.svc.cloud.microsoft/.well-known/oauth-protected-resource/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools"'
export const AGENT365_MAIL_PRM_JSON =
'{"resource_name":"mcp_MailTools","resource":"https://agent365.svc.cloud.microsoft/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools","authorization_servers":["https://login.microsoftonline.com/organizations/v2.0"],"scopes_supported":["https://agent365.svc.cloud.microsoft/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools/.default","openid","profile","offline_access"],"bearer_methods_supported":["header"]}'
export const ENTRA_ORGANIZATIONS_OIDC_JSON =
'{"token_endpoint":"https://login.microsoftonline.com/organizations/oauth2/v2.0/token","token_endpoint_auth_methods_supported":["client_secret_post","private_key_jwt","client_secret_basic","self_signed_tls_client_auth"],"jwks_uri":"https://login.microsoftonline.com/organizations/discovery/v2.0/keys","response_modes_supported":["query","fragment","form_post"],"subject_types_supported":["pairwise"],"id_token_signing_alg_values_supported":["RS256"],"response_types_supported":["code","id_token","code id_token","id_token token"],"scopes_supported":["openid","profile","email","offline_access"],"issuer":"https://login.microsoftonline.com/{tenantid}/v2.0","request_uri_parameter_supported":false,"userinfo_endpoint":"https://graph.microsoft.com/oidc/userinfo","authorization_endpoint":"https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize","device_authorization_endpoint":"https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode","http_logout_supported":true,"frontchannel_logout_supported":true,"end_session_endpoint":"https://login.microsoftonline.com/organizations/oauth2/v2.0/logout","claims_supported":["sub","iss","cloud_instance_name","cloud_instance_host_name","cloud_graph_host_name","msgraph_host","aud","exp","iat","auth_time","acr","nonce","preferred_username","name","tid","ver","at_hash","c_hash","email"],"kerberos_endpoint":"https://login.microsoftonline.com/organizations/kerberos","mtls_endpoint_aliases":{"token_endpoint":"https://mtlsauth.microsoft.com/organizations/oauth2/v2.0/token"},"tls_client_certificate_bound_access_tokens":true,"tenant_region_scope":null,"cloud_instance_name":"microsoftonline.com","cloud_graph_host_name":"graph.windows.net","msgraph_host":"graph.microsoft.com","rbac_url":"https://pas.windows.net"}'
export const ENTRA_TENANT_OIDC_JSON =
'{"token_endpoint":"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token","token_endpoint_auth_methods_supported":["client_secret_post","private_key_jwt","client_secret_basic","self_signed_tls_client_auth"],"jwks_uri":"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/discovery/v2.0/keys","response_modes_supported":["query","fragment","form_post"],"subject_types_supported":["pairwise"],"id_token_signing_alg_values_supported":["RS256"],"response_types_supported":["code","id_token","code id_token","id_token token"],"scopes_supported":["openid","profile","email","offline_access"],"issuer":"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0","request_uri_parameter_supported":false,"userinfo_endpoint":"https://graph.microsoft.com/oidc/userinfo","authorization_endpoint":"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/authorize","device_authorization_endpoint":"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/devicecode","http_logout_supported":true,"frontchannel_logout_supported":true,"end_session_endpoint":"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/logout","claims_supported":["sub","iss","cloud_instance_name","cloud_instance_host_name","cloud_graph_host_name","msgraph_host","aud","exp","iat","auth_time","acr","nonce","preferred_username","name","tid","ver","at_hash","c_hash","email"],"kerberos_endpoint":"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/kerberos","mtls_endpoint_aliases":{"token_endpoint":"https://mtlsauth.microsoft.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token"},"tls_client_certificate_bound_access_tokens":true,"tenant_region_scope":"WW","cloud_instance_name":"microsoftonline.com","cloud_graph_host_name":"graph.windows.net","msgraph_host":"graph.microsoft.com","rbac_url":"https://pas.windows.net"}'
export const ENTRA_UNKNOWN_TENANT_OIDC_400_JSON =
'{"error":"invalid_tenant","error_description":"AADSTS90002: Tenant \'00000000-0000-0000-0000-000000000001\' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant. Trace ID: fd7c437e-5de4-418f-a92d-2542f3ff1e00 Correlation ID: f396dc2b-aa03-4985-b73a-a44d76d054af Timestamp: 2026-10-21 14:15:01Z","error_codes":[90002],"timestamp":"2026-10-21 14:15:01Z","trace_id":"fd7c437e-5de4-418f-a92d-2542f3ff1e00","correlation_id":"f396dc2b-aa03-4985-b73a-a44d76d054af","error_uri":"https://login.microsoftonline.com/error?code=90002"}'
export const ENTRA_TENANT_AUTHORITY =
'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0'
/** OIDC metadata both Entra pilots serve: the real tenant, `organizations` and an unknown tenant. */
const ENTRA_AS = {
url: `${ENTRA_TENANT_AUTHORITY}/.well-known/openid-configuration`,
json: ENTRA_TENANT_OIDC_JSON,
}
const ENTRA_AS_EXTRA = [
{
url: 'https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration',
status: 200,
json: ENTRA_ORGANIZATIONS_OIDC_JSON,
},
{
url: 'https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0/.well-known/openid-configuration',
status: 400,
json: ENTRA_UNKNOWN_TENANT_OIDC_400_JSON,
},
]
/** Work IQ: PRM advertises the multi-tenant `organizations` authority and a GUID-form scope. */
export const ENTRA_WORKIQ_PILOT: PilotFixture = {
name: 'entra-workiq',
mcpUrl: 'https://workiq.svc.cloud.microsoft/mcp',
wwwAuthenticate: WORKIQ_WWW_AUTHENTICATE,
prm: {
url: 'https://workiq.svc.cloud.microsoft/.well-known/oauth-protected-resource/mcp',
json: WORKIQ_PRM_JSON,
},
as: ENTRA_AS,
asExtra: ENTRA_AS_EXTRA,
}
/** Agent 365 Mail (per-app server): same Entra authority, URL-form `.default` scope plus OIDC scopes. */
export const ENTRA_AGENT365_MAIL_PILOT: PilotFixture = {
name: 'entra-agent365-mail',
mcpUrl:
'https://agent365.svc.cloud.microsoft/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools',
wwwAuthenticate: AGENT365_MAIL_WWW_AUTHENTICATE,
prm: {
url: 'https://agent365.svc.cloud.microsoft/.well-known/oauth-protected-resource/agents/tenants/72f988bf-86f1-41af-91ab-2d7cd011db47/servers/mcp_MailTools',
json: AGENT365_MAIL_PRM_JSON,
},
as: ENTRA_AS,
asExtra: ENTRA_AS_EXTRA,
}
// Synthetic Entra pilots: the real Work IQ pilot with ONE PRM field altered (parsed and
// re-serialized, every other byte as captured). Each stands for a PRM the platform must
// handle but no live server is known to emit — hostile or misconfigured scopes, a PRM
// that already names the tenant — so the change is the only invented part.
export function workIqPilotWithPrm(
name: string,
mutate: (prm: Record<string, unknown>) => void
): PilotFixture {
const prm = JSON.parse(WORKIQ_PRM_JSON) as Record<string, unknown>
mutate(prm)
return {
...ENTRA_WORKIQ_PILOT,
name,
prm: { ...ENTRA_WORKIQ_PILOT.prm, json: JSON.stringify(prm) },
}
}
/** `scopes_supported` → a Microsoft Graph URL scope: a PRM asking for a token for another API. */
export const ENTRA_GRAPH_SCOPE_PILOT = workIqPilotWithPrm('entra-graph-scope', prm => {
prm.scopes_supported = ['https://graph.microsoft.com/Mail.ReadWrite']
})
/** `authorization_servers` → the tenant authority: a PRM that already names the tenant. */
export const ENTRA_TENANT_PRM_PILOT = workIqPilotWithPrm('entra-tenant-prm', prm => {
prm.authorization_servers = [ENTRA_TENANT_AUTHORITY]
})
/** `scopes_supported` → a GUID-form scope of an app this platform does not know. */
export const ENTRA_UNKNOWN_GUID_PILOT = workIqPilotWithPrm('entra-unknown-guid', prm => {
prm.scopes_supported = ['11111111-2222-3333-4444-555555555555/Tools.Read']
})
/** `scopes_supported` → a SharePoint Online GUID-form scope: a high-impact first-party API. */
export const ENTRA_SHAREPOINT_SCOPE_PILOT = workIqPilotWithPrm('entra-sharepoint-scope', prm => {
prm.scopes_supported = ['00000003-0000-0ff1-ce00-000000000000/AllSites.Read']
})
/** `scopes_supported` → an empty scope beside Work IQ's own: the empty one alone breaks the audience rule. */
export const ENTRA_EMPTY_SCOPE_PILOT = workIqPilotWithPrm('entra-empty-scope', prm => {
prm.scopes_supported = ['', 'fdcc1f02-fc51-4226-8753-f668596af7f7/WorkIQAgent.Ask']
})
/** `scopes_supported` removed: the requested scopes fall back to the AS's OIDC-only list. */
export const ENTRA_NO_SCOPES_PILOT = workIqPilotWithPrm('entra-no-scopes', prm => {
delete prm.scopes_supported
})
/**
* Build a {@link PinnedTransport}-shaped mock from a pilot fixture: a 401 (with
* WWW-Authenticate) on the MCP probe when the fixture has a hint, 200+JSON on the
* served well-known URLs, and 404 on the URLs the real server does not serve.
* Mirrors the real HTTP responses so the discovery code path is exercised, not a
* hand-invented one. Discovery now fetches through the IP-pinned `node:https`
* transport (H2), so the test double is a transport, not a `fetch`.
*/
// ─── DCR fixtures (spec 02 C2, DEC-19) ──────────────────────────────────────
//
// The GET-able parts (PRM + AS metadata) are derived from the REAL Notion probe
// (above) by DOCUMENTED SUBTRACTION, per DEC-19: removing
// `client_id_metadata_document_supported` pushes the mode selector off CIMD onto
// DCR (Notion advertises a `/register` endpoint). Dropping `none` from the auth
// methods additionally forces DCR-CONFIDENTIAL. Nothing here is hand-invented —
// the fields removed are the exact ones the real Notion AS emits.
function subtractedNotionAs(mutate: (as: Record<string, unknown>) => void): string {
const as = JSON.parse(NOTION_AS_JSON) as Record<string, unknown>
mutate(as)
return JSON.stringify(as)
}
/** Real Notion probe minus CIMD support → DCR, and `none` kept → public client. */
export const DCR_PUBLIC_AS_JSON = subtractedNotionAs(as => {
delete as.client_id_metadata_document_supported
})
/** Real Notion probe minus CIMD support AND minus `none` → DCR, confidential. */
export const DCR_CONFIDENTIAL_AS_JSON = subtractedNotionAs(as => {
delete as.client_id_metadata_document_supported
as.token_endpoint_auth_methods_supported = ['client_secret_basic', 'client_secret_post']
})
/** A DCR-forced pilot (public or confidential) reusing Notion's real PRM + URLs. */
export function dcrPilot(mode: 'public' | 'confidential'): PilotFixture {
return {
name: `dcr-${mode}`,
mcpUrl: 'https://mcp.notion.com/mcp',
prm: {
url: 'https://mcp.notion.com/.well-known/oauth-protected-resource',
json: NOTION_PRM_JSON,
},
prmNotFound: ['https://mcp.notion.com/.well-known/oauth-protected-resource/mcp'],
as: {
url: 'https://mcp.notion.com/.well-known/oauth-authorization-server',
json: mode === 'public' ? DCR_PUBLIC_AS_JSON : DCR_CONFIDENTIAL_AS_JSON,
},
}
}
/** The registration endpoint Notion advertises (target of the DCR POST). */
export const DCR_REGISTRATION_ENDPOINT = 'https://mcp.notion.com/register'
// The RFC 7591 §3.2.1 registration RESPONSE fixtures below are:
// NOT probed — derived from RFC 7591 §3.2.1, not a live probe.
// A DCR registration response can only be obtained by a side-effecting POST that
// creates a persistent client at a third party (DEC-19) — not repeatable in CI and
// an external-effect action. These encode the RFC 7591 SHAPE (the contract a real
// AS honours), which is what makes `registerDynamicClient`'s parse path reachable;
// the VALUES are illustrative and no POST is ever made to a third party.
export const DCR_PUBLIC_REGISTRATION_RESPONSE = {
client_id: 'dyn-public-6f1c2a',
client_id_issued_at: 1_758_326_400,
token_endpoint_auth_method: 'none',
redirect_uris: ['https://control.example.com/api/v1/oauth-callback/remote'],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
} as const
export const DCR_CONFIDENTIAL_REGISTRATION_RESPONSE = {
client_id: 'dyn-conf-9b3d7e',
// fixture value, not a live secret — DEC-19
client_secret: 'fixture-client-secret-not-probed',
client_id_issued_at: 1_758_326_400,
client_secret_expires_at: 0, // RFC 7591: 0 ⇒ non-expiring ⇒ stored NULL
// fixture value, not a live RFC 7592 bearer — DEC-19
registration_access_token: 'fixture-reg-access-token-not-probed',
registration_client_uri: 'https://mcp.notion.com/register/dyn-conf-9b3d7e',
token_endpoint_auth_method: 'client_secret_post',
redirect_uris: ['https://control.example.com/api/v1/oauth-callback/remote'],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
} as const
/** Same confidential response but the AS overrides the method to one we cannot present. */
export const DCR_BASIC_REGISTRATION_RESPONSE = {
...DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
token_endpoint_auth_method: 'client_secret_basic',
} as const
/**
* The EXACT RFC 7591 §3.2.1 body Vercel returned (HTTP 201) to a confidential
* (`client_secret_post`) DCR request, captured live from
* `https://api.vercel.com/login/oauth/register`. Vercel DOWNGRADES the client to
* public — `token_endpoint_auth_method: "none"`, NO `client_secret` — which is
* legitimate per RFC 7591 (the AS is the final authority on the auth method): clerum
* requested confidential only because Vercel's AS metadata omits `none` from
* `token_endpoint_auth_methods_supported`. Kept as the VERBATIM wire string (not a
* hand-shaped object) so `registerDynamicClient`'s parse path sees exactly what
* Vercel emits — the downgrade shape is observed, never invented.
*/
export const DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON =
'{"client_id":"cl_WbdtcToDrMR4ZHvXLGAmbfoYCsQjMeS8","token_endpoint_auth_method":"none","grant_types":["authorization_code","refresh_token"],"response_types":["code"],"client_name":"Evenfire","redirect_uris":["http://127.0.0.1:8090/api/v1/oauth-callback/remote"]}'
export const DCR_VERCEL_DOWNGRADE_REGISTRATION_RESPONSE = JSON.parse(
DCR_VERCEL_DOWNGRADE_REGISTRATION_JSON
) as { client_id: string; token_endpoint_auth_method: string; [k: string]: unknown }
/**
* Adversarial 2xx: a PUBLIC assignment (`token_endpoint_auth_method: "none"`) that
* ALSO echoes a `client_secret`. The wire shape is the Vercel downgrade body plus an
* injected `client_secret` — kept as the VERBATIM string, not a hand-shaped object.
* A public client has no secret, so control-api must classify it public and DISCARD
* the echoed secret (never persist or log it).
*/
export const DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON =
'{"client_id":"cl_PublicWithEchoedSecret_x91","token_endpoint_auth_method":"none","client_secret":"echoed-secret-must-be-discarded","grant_types":["authorization_code","refresh_token"],"response_types":["code"],"client_name":"Evenfire","redirect_uris":["http://127.0.0.1:8090/api/v1/oauth-callback/remote"]}'
export const DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_RESPONSE = JSON.parse(
DCR_PUBLIC_WITH_ECHOED_SECRET_REGISTRATION_JSON
) as { client_id: string; token_endpoint_auth_method: string; client_secret: string }
/**
* Adversarial 2xx: a NON-STRING `token_endpoint_auth_method` (a number) injected by
* an untrusted AS. Verbatim wire string. Must fail closed to `auth_method_unsupported`
* rather than let the garbage value flow to the effective-mode derivation.
*/
export const DCR_NONSTRING_AUTH_METHOD_REGISTRATION_JSON =
'{"client_id":"cl_NonStringAuthMethod","token_endpoint_auth_method":42,"registration_client_uri":"https://mcp.notion.com/register/cl_NonStringAuthMethod","registration_access_token":"fixture-reg-access-token-not-probed"}'
export interface RecordedDcrCall {
url: string
method: string
headers: Record<string, string>
body?: string
}
/**
* A {@link PinnedTransport} stub for the DCR POST (and the RFC 7592 rollback
* DELETE), recording every call so a test can assert the single-hop POST and the
* best-effort management DELETE happened. Zero network (DEC-19). The registration
* endpoint returns `responseJson` at `status`; the management URI answers 204 to a
* DELETE; anything else 404s.
*/
export function makeDcrTransport(opts: {
registrationEndpoint?: string
responseJson: string
status?: number
managementUri?: string
/**
* How the AS reports `redirect_uris` in the registration response:
* - `'requested'`: echo the `redirect_uris` of the request actually POSTed, as an
* RFC 7591 §3.2.1 AS does. Needed wherever the requested URI is only known at
* install time (the per-server DCR URI carries a fresh install nonce).
* - `'omit'`: drop the field.
* - a string array: report these instead (an AS that registered something else).
* Unset: `responseJson` verbatim.
*/
redirectUris?: 'requested' | 'omit' | string[]
}): { transport: PinnedTransport; calls: RecordedDcrCall[] } {
const registrationEndpoint = opts.registrationEndpoint ?? DCR_REGISTRATION_ENDPOINT
const status = opts.status ?? 201
const calls: RecordedDcrCall[] = []
const transport: PinnedTransport = async ({ url, method, headers, body }) => {
calls.push({ url, method, headers, body })
if (url === registrationEndpoint && method === 'POST') {
let bodyText = opts.responseJson
if (opts.redirectUris !== undefined) {
const response = JSON.parse(opts.responseJson) as Record<string, unknown>
if (opts.redirectUris === 'omit') delete response.redirect_uris
else if (opts.redirectUris === 'requested')
response.redirect_uris = (
JSON.parse(body ?? '{}') as { redirect_uris?: unknown }
).redirect_uris
else response.redirect_uris = opts.redirectUris
bodyText = JSON.stringify(response)
}
return {
status,
headers: { 'content-type': 'application/json' },
bodyText,
}
}
if (method === 'DELETE') {
return { status: 204, headers: {}, bodyText: '' }
}
return { status: 404, headers: {}, bodyText: 'unexpected url' }
}
return { transport, calls }
}
/**
* A minimal in-memory `dynamic_clients` DbClient for the store + saga tests. It is
* a TEST HARNESS (not a cross-layer fixture, T1): it mirrors the exact parameter
* order of `dynamicClientStore.ts`'s own statements so the saga runs end-to-end with
* zero real Postgres. The encrypted envelope it stores is produced by the real
* `encryptOAuthSecret` inside the store, never hand-written.
*
* It models the install-identity statements the route now drives: the pending INSERT
* (`ON CONFLICT DO NOTHING RETURNING id`), the legacy upsert (`ON CONFLICT DO UPDATE`),
* the bind UPDATE, the reclaim guarded UPDATE, and both DELETE shapes (by-install and
* by-name). The AUTHORITATIVE SQL semantics — real ON CONFLICT, the reclaim guard
* race — are certified by the real-Postgres suite
* (`oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts`); this
* harness only lets the route-level wiring (classify → HTTP code, which 7592 DELETE
* fires) be asserted offline.
*/
export function makeInMemoryDynamicClientsDb(): {
db: DbClient
rows: Map<string, Record<string, unknown>>
} {
const rows = new Map<string, Record<string, unknown>>()
const keyOf = (owner: unknown, ns: unknown, name: unknown) => `${owner}/${ns}/${name}`
let idSequence = 0
const db = {
query: async (text: string, values: unknown[] = []) => {
if (text.includes('INSERT INTO dynamic_clients')) {
const [
owner_kind,
server_namespace,
server_name,
issuer,
client_id,
client_mode,
client_secret_encrypted,
registration_access_token_encrypted,
registration_client_uri,
client_id_issued_at,
client_secret_expires_at,
// Present only on the pending INSERT (12th param); undefined for the upsert.
install_id,
] = values
const key = keyOf(owner_kind, server_namespace, server_name)
const existing = rows.get(key)
// Pending INSERT: ON CONFLICT DO NOTHING — never clobber, signal via rowCount.
if (text.includes('DO NOTHING')) {
if (existing) return { rows: [], rowCount: 0 }
const id = ++idSequence
rows.set(key, {
id,
owner_kind,
server_namespace,
server_name,
issuer,
client_id,
client_mode,
client_secret_encrypted,
registration_access_token_encrypted,
registration_client_uri,
client_id_issued_at,
client_secret_expires_at,
install_id: install_id ?? null,
cr_uid: null,
created_at: new Date(),
updated_at: new Date(),
})
return { rows: [{ id }], rowCount: 1 }
}
// Legacy upsert: ON CONFLICT DO UPDATE overwrites the creds in place; it does
// NOT touch install_id/cr_uid, so those survive a conflict (default NULL on a
// fresh insert).
rows.set(key, {
id: existing?.id ?? ++idSequence,
owner_kind,
server_namespace,
server_name,
issuer,
client_id,
client_mode,
client_secret_encrypted,
registration_access_token_encrypted,
registration_client_uri,
client_id_issued_at,
client_secret_expires_at,
install_id: existing?.install_id ?? null,
cr_uid: existing?.cr_uid ?? null,
created_at: existing?.created_at ?? new Date(),
updated_at: new Date(),
})
return { rows: [], rowCount: 1 }
}
if (text.includes('DELETE FROM dynamic_clients')) {
const [owner_kind, server_namespace, server_name, fourth] = values
const key = keyOf(owner_kind, server_namespace, server_name)
const row = rows.get(key)
// Claim-delete (teardown): WHERE (cr_uid = $4 OR legacy) RETURNING the handle.
// Deletes the row bound to this uid or a legacy row (both identity cols NULL);
// a pending row or a row bound to a different uid does NOT match.
if (text.includes('RETURNING')) {
if (row && (row.cr_uid === fourth || (row.install_id == null && row.cr_uid == null))) {
rows.delete(key)
return {
rows: [
{
registration_client_uri: row.registration_client_uri,
registration_access_token_encrypted: row.registration_access_token_encrypted,
},
],
rowCount: 1,
}
}
return { rows: [], rowCount: 0 }
}
// By-install DELETE (saga compensation): remove only when the install_id matches.
if (values.length === 4) {
if (row && row.install_id === fourth) {
rows.delete(key)
return { rows: [], rowCount: 1 }
}
return { rows: [], rowCount: 0 }
}
// By-name DELETE (legacy).
const existed = rows.delete(key)
return { rows: [], rowCount: existed ? 1 : 0 }
}
if (text.includes('UPDATE dynamic_clients')) {
const key = keyOf(values[0], values[1], values[2])
const row = rows.get(key)
if (!row) return { rows: [], rowCount: 0 }
// Reclaim: one guard on the observed identity — id = $13 AND install_id IS
// NOT DISTINCT FROM $14 AND cr_uid IS NOT DISTINCT FROM $15 — RETURNING the
// OLD row's RFC 7592 handle.
if (text.includes('IS NOT DISTINCT FROM')) {
const [
,
,
,
issuer,
client_id,
client_mode,
client_secret_encrypted,
registration_access_token_encrypted,
registration_client_uri,
client_id_issued_at,
client_secret_expires_at,
newInstallId,
observedId,
observedInstallId,
observedCrUid,
] = values
if (
String(row.id) !== String(observedId) ||
(row.install_id ?? null) !== (observedInstallId ?? null) ||
(row.cr_uid ?? null) !== (observedCrUid ?? null)
) {
return { rows: [], rowCount: 0 }
}
const oldHandle = {
registration_client_uri: row.registration_client_uri,
registration_access_token_encrypted: row.registration_access_token_encrypted,
}
Object.assign(row, {
issuer,
client_id,
client_mode,
client_secret_encrypted,
registration_access_token_encrypted,
registration_client_uri,
client_id_issued_at,
client_secret_expires_at,
install_id: newInstallId,
cr_uid: null,
updated_at: new Date(),
})
return { rows: [oldHandle], rowCount: 1 }
}
// Bind: WHERE install_id = $4 AND cr_uid IS NULL, SET cr_uid = $5.
const [, , , installId, crUid] = values
if (row.install_id === installId && row.cr_uid == null) {
row.cr_uid = crUid
row.updated_at = new Date()
return { rows: [], rowCount: 1 }
}
return { rows: [], rowCount: 0 }
}
if (
text.includes('FROM dynamic_clients') &&
text.includes('client_id = $3') &&
text.includes('AND issuer = $4')
) {
// Existence by (issuer, client_id) within a namespace (pre-registered uniqueness).
// Matched on the issuer predicate too: a query that dropped it must not be
// answered as if it still filtered by issuer.
const [owner_kind, server_namespace, client_id, issuer] = values
const hit = [...rows.values()].some(
row =>
row.owner_kind === owner_kind &&
row.server_namespace === server_namespace &&
row.client_id === client_id &&
row.issuer === issuer
)
return hit ? { rows: [{ '?column?': 1 }], rowCount: 1 } : { rows: [], rowCount: 0 }
}
if (text.includes('FROM dynamic_clients')) {
const [owner_kind, server_namespace, server_name] = values
const row = rows.get(keyOf(owner_kind, server_namespace, server_name))
// Return a SNAPSHOT (shallow copy), as a real SELECT does: a later UPDATE must
// not retroactively mutate a row already read. `age_ms` mirrors the store's
// `NOW() - updated_at` column, measured at read time.
if (!row) return { rows: [], rowCount: 0 }
const ageMs = Date.now() - (row.updated_at as Date).getTime()
return { rows: [{ ...row, age_ms: ageMs }], rowCount: 1 }
}
return { rows: [], rowCount: 0 }
},
} as unknown as DbClient
return { db, rows }
}
/**
* The real POST `initialize` 401 challenge the four CIMD pilots emit (Notion/Canva/
* Linear/Sentry, sondeo 2026-09-25): a Bearer challenge = transport ALIVE, token
* required. Only presence matters to the probe's `challenge` classification.
*/
const CIMD_INITIALIZE_CHALLENGE = 'Bearer realm="OAuth", error="invalid_token"'
export function makeDiscoveryTransport(pilot: PilotFixture): PinnedTransport {
const jsonByUrl = new Map<string, string>([
[pilot.prm.url, pilot.prm.json],
[pilot.as.url, pilot.as.json],
...(pilot.prmRoot ? ([[pilot.prmRoot.url, pilot.prmRoot.json]] as [string, string][]) : []),
])
const notFound = new Set(pilot.prmNotFound ?? [])
const extraByUrl = new Map((pilot.asExtra ?? []).map(entry => [entry.url, entry]))
return async ({ url, method }) => {
// POST → the transport probe (tokenless `initialize`). Per-URL `initialize` table
// first (Vercel `/mcp`→404, `/`→200); otherwise the typed MCP URL defaults to the
// real 401 challenge shape (transport alive). Method is undefined-safe.
if (method === 'POST') {
const probe = pilot.initialize?.[url]
if (probe) return { status: probe.status, headers: probe.headers, bodyText: '' }
if (url === pilot.mcpUrl) {
return {
status: 401,
headers: { 'www-authenticate': pilot.wwwAuthenticate ?? CIMD_INITIALIZE_CHALLENGE },
bodyText: '',
}
}
return { status: 404, headers: { 'content-type': 'text/html' }, bodyText: 'not found' }
}
// GET (discovery): MCP probe → 401 with the challenge header when the fixture has one.
if (url === pilot.mcpUrl) {
if (pilot.wwwAuthenticate) {
return { status: 401, headers: { 'www-authenticate': pilot.wwwAuthenticate }, bodyText: '' }
}
// No challenge advertised — probe returns a plain 401 with no hint.
return { status: 401, headers: {}, bodyText: '' }
}
const body = jsonByUrl.get(url)
if (body !== undefined) {
return { status: 200, headers: { 'content-type': 'application/json' }, bodyText: body }
}
const extra = extraByUrl.get(url)
if (extra) {
return {
status: extra.status,
headers: { 'content-type': 'application/json' },
bodyText: extra.json,
}
}
if (notFound.has(url)) return { status: 404, headers: {}, bodyText: 'not found' }
return { status: 404, headers: {}, bodyText: 'unexpected url' }
}
}
/** Wrap a transport so a test can assert which URLs discovery requested (and which it never did). */
export function recordingTransport(inner: PinnedTransport): {
transport: PinnedTransport
requestedUrls: string[]
} {
const requestedUrls: string[] = []
const transport: PinnedTransport = async request => {
requestedUrls.push(request.url)
return inner(request)
}
return { transport, requestedUrls }
}