源码快照 @ 2026-09-02 (source-only, 剔除非源码素材)

This commit is contained in:
agent-radar committed 2026-09-02 01:05:41 +08:00
commit 04bac1f6e2
2200 files changed
+489415

No files matched your search

@@ -0,0 +1,220 @@
import assert from "node:assert/strict"
import test from "node:test"
import { once } from "node:events"
import { createConnection } from "node:net"
import {
createDefaultScenario,
createEnterpriseMcpMockServer,
getProviderProfile,
} from "../src/index.js"
import { InstanceState } from "../src/runtime/instance-state.js"
const oauthClientSecret = "synthetic-test-client-secret-32-bytes"
test("event and state buffers are capped, expire, and redact known secrets", () => {
let now = 1_700_000_000_000
let counter = 0
const environment = {
now: () => now,
randomId: () => `id-${++counter}`,
opaqueValue: (prefix: string) => `${prefix}-${++counter}`,
}
const scenario = createDefaultScenario()
const profile = getProviderProfile(scenario.profileId)
const state = new InstanceState(scenario, profile, [oauthClientSecret], environment)
for (let index = 0; index < 600; index += 1) {
state.emit({
correlationId: `correlation-${index}`,
scenario,
phase: "CONFIGURATION",
direction: "internal",
kind: "lifecycle",
outcome: "completed",
summary: "Synthetic bounded event",
details: {
safe: `Bearer access-token-${index} ${oauthClientSecret}`,
clientSecret: oauthClientSecret,
},
})
}
assert.equal(state.events().length, 500)
const serialized = JSON.stringify(state.events())
assert.equal(serialized.includes(oauthClientSecret), false)
assert.equal(serialized.includes("access-token-"), false)
for (let index = 0; index < 120; index += 1) {
state.putClient({
clientId: `client-${index}`,
clientSecret: `secret-${index}`,
redirectUris: ["http://127.0.0.1:19876/callback"],
tokenEndpointAuthMethod: "client_secret_post",
createdAt: now,
expiresAt: now + 3_600_000,
})
}
assert.equal(state.clients.size, 100)
for (let index = 0; index < 120; index += 1) {
state.putAuthorizationCode({
code: `code-${index}`,
clientId: `client-${index}`,
redirectUri: "http://127.0.0.1:19876/callback",
codeChallenge: `challenge-${index}`,
resource: "http://127.0.0.1:9999/mcp",
scopes: ["mcp_server"],
expiresAt: now + 1_000,
})
state.putToken({
accessToken: `access-${index}`,
familyId: `family-${index}`,
clientId: `client-${index}`,
resource: "http://127.0.0.1:9999/mcp",
scopes: ["mcp_server"],
subject: `subject-${index}`,
expiresAt: now + 1_000,
})
state.putRefreshToken({
refreshToken: `refresh-${index}`,
familyId: `family-${index}`,
clientId: `client-${index}`,
resource: "http://127.0.0.1:9999/mcp",
scopes: ["mcp_server"],
subject: `subject-${index}`,
expiresAt: now + 2_000,
})
state.putSession({
sessionId: `session-${index}`,
tokenFamilyId: `family-${index}`,
operationNamespace: `client-${index}\u0000subject-${index}\u0000resource`,
profileId: profile.id,
protocolVersion: scenario.protocol.version,
scenarioRevision: scenario.revision,
expiresAt: now + 1_000,
initialized: true,
})
}
assert.equal(state.authorizationCodes.size, 100)
assert.equal(state.tokens.size, 100)
assert.equal(state.refreshTokens.size, 100)
assert.equal(state.sessions.size, 100)
for (let index = 0; index < 1_020; index += 1) {
const prepared = state.prepareOperation("test-family", "create_incident", `idempotency-${index}`, { value: index })
if (prepared.kind === "prepared") state.transitionOperation(prepared.operation.operationId, "responded", `result-${index}`)
}
assert.equal(state.operations.size, 1000)
for (let index = 0; index < 120; index += 1) state.faultCounters.set(`fault-${index}`, index)
state.maintainBounds()
assert.equal(state.faultCounters.size, 100)
now += 3_600_001
state.maintainBounds()
assert.equal(state.clients.size, 0)
assert.equal(state.authorizationCodes.size, 0)
assert.equal(state.tokens.size, 0)
assert.equal(state.refreshTokens.size, 0)
assert.equal(state.sessions.size, 0)
now += 86_400_001
state.maintainBounds()
assert.equal(state.operations.size, 0)
})
test("stop and reset drain an incomplete active request and leave no orphan listener", async () => {
const scenario = createDefaultScenario("synthetic-enterprise-oauth-mcp")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
const firstBaseUrl = server.baseUrl
const firstUrl = new URL(firstBaseUrl)
const firstSocket = createConnection({ host: firstUrl.hostname, port: Number(firstUrl.port) })
firstSocket.on("error", () => undefined)
await once(firstSocket, "connect")
firstSocket.write(
"POST /oauth/register HTTP/1.1\r\n" +
`Host: ${firstUrl.host}\r\n` +
"Content-Type: application/json\r\n" +
"Content-Length: 100\r\n" +
"Connection: keep-alive\r\n\r\n" +
"{",
)
const stopped = await server.stop()
assert.equal(stopped.status, "stopped")
assert.equal(stopped.counts.sessions, 0)
assert.equal(stopped.counts.tokens, 0)
await assert.rejects(fetch(new URL("/health", firstBaseUrl)))
await server.start()
const secondBaseUrl = server.baseUrl
const secondUrl = new URL(secondBaseUrl)
const secondSocket = createConnection({ host: secondUrl.hostname, port: Number(secondUrl.port) })
secondSocket.on("error", () => undefined)
await once(secondSocket, "connect")
secondSocket.write(
"POST /oauth/register HTTP/1.1\r\n" +
`Host: ${secondUrl.host}\r\n` +
"Content-Type: application/json\r\n" +
"Content-Length: 100\r\n" +
"Connection: keep-alive\r\n\r\n" +
"{",
)
const reset = await server.reset()
assert.equal(reset.status, "running")
assert.equal(reset.counts.sessions, 0)
assert.equal(reset.counts.tokens, 0)
const health = await fetch(new URL("/health", server.baseUrl))
assert.equal(health.status, 200)
await server.stop()
})
test("only a responded mutation can be reported as an idempotent duplicate", () => {
let counter = 0
const scenario = createDefaultScenario()
const state = new InstanceState(
scenario,
getProviderProfile(scenario.profileId),
[oauthClientSecret],
{ now: Date.now, randomId: () => `id-${++counter}`, opaqueValue: (prefix) => `${prefix}-${++counter}` },
)
const prepared = state.prepareOperation("family-a", "create_incident", "stable-idempotency-key", { value: 1 })
assert.equal(prepared.kind, "prepared")
assert.equal(state.prepareOperation("family-a", "create_incident", "stable-idempotency-key", { value: 1 }).kind, "reconcile")
if (prepared.kind !== "prepared") throw new Error("Expected prepared operation")
state.transitionOperation(prepared.operation.operationId, "committed", "synthetic:result")
assert.equal(state.prepareOperation("family-a", "create_incident", "stable-idempotency-key", { value: 1 }).kind, "reconcile")
state.transitionOperation(prepared.operation.operationId, "responded", "synthetic:result")
assert.equal(state.prepareOperation("family-a", "create_incident", "stable-idempotency-key", { value: 1 }).kind, "duplicate")
assert.equal(state.prepareOperation("family-b", "create_incident", "stable-idempotency-key", { value: 1 }).kind, "prepared")
})
test("bounded eviction never forgets an unresolved mutation outcome", () => {
let counter = 0
const scenario = createDefaultScenario()
const state = new InstanceState(
scenario,
getProviderProfile(scenario.profileId),
[oauthClientSecret],
{ now: Date.now, randomId: () => `id-${++counter}`, opaqueValue: (prefix) => `${prefix}-${++counter}` },
)
const critical = state.prepareOperation("critical-client", "create_incident", "critical-key", { value: "critical" })
if (critical.kind !== "prepared") throw new Error("Expected critical operation to prepare")
state.transitionOperation(critical.operation.operationId, "indeterminate", "critical-result")
for (let index = 0; index < 1_100; index += 1) {
const filler = state.prepareOperation("filler-client", "create_incident", `filler-${index}`, { value: index })
if (filler.kind === "prepared") state.transitionOperation(filler.operation.operationId, "responded", `result-${index}`)
}
assert.equal(state.operations.has(critical.operation.operationId), true)
assert.equal(state.prepareOperation("critical-client", "create_incident", "critical-key", { value: "critical" }).kind, "reconcile")
assert.equal(state.operations.size, 1000)
})
test("a ledger full of unresolved outcomes rejects new mutations instead of evicting evidence", () => {
let counter = 0
const scenario = createDefaultScenario()
const state = new InstanceState(
scenario,
getProviderProfile(scenario.profileId),
[oauthClientSecret],
{ now: Date.now, randomId: () => `id-${++counter}`, opaqueValue: (prefix) => `${prefix}-${++counter}` },
)
for (let index = 0; index < 1_000; index += 1) {
assert.equal(state.prepareOperation("capacity-client", "create_incident", `unresolved-${index}`, { value: index }).kind, "prepared")
}
assert.equal(state.prepareOperation("capacity-client", "create_incident", "one-too-many", { value: 1_001 }).kind, "capacity")
assert.equal(state.operations.size, 1_000)
})
@@ -0,0 +1,33 @@
import assert from "node:assert/strict"
import { spawnSync } from "node:child_process"
import { fileURLToPath } from "node:url"
import test from "node:test"
import { createCliScenario } from "../src/cli-scenario.js"
test("CLI rejects an unknown active fault before starting the server", () => {
const result = spawnSync(
process.execPath,
["--import", "tsx", fileURLToPath(new URL("../src/cli.ts", import.meta.url))],
{
encoding: "utf8",
env: {
...process.env,
PROFILE_ID: "synthetic-enterprise-oauth-mcp",
ACTIVE_FAULT_ID: "not-a-real-fault",
},
},
)
assert.equal(result.status, 1)
assert.match(result.stderr, /Invalid ACTIVE_FAULT_ID 'not-a-real-fault'/)
assert.match(result.stderr, /Valid ids: .*oauth-missing-auth-challenge/)
})
test("CLI scenario activates a known fault with the always trigger", () => {
const scenario = createCliScenario("synthetic-enterprise-oauth-mcp", "oauth-issuer-mismatch")
assert.deepEqual(scenario.activeFault, {
id: "oauth-issuer-mismatch",
trigger: { occurrence: "always" },
})
})
@@ -0,0 +1,238 @@
import assert from "node:assert/strict"
import test from "node:test"
import {
createDefaultScenario,
createFaultScenario,
getProviderProfile,
isSafeOAuthRedirectUri,
listFaultDefinitions,
listProviderProfiles,
scenarioSchema,
toolInputSchemaSchema,
validateToolArguments,
type EnterpriseMcpScenario,
type FaultDefinition,
type MockTool,
type ProviderProfile,
} from "../src/index.js"
function compileTimeScenarioReadonly(scenario: EnterpriseMcpScenario): void {
// @ts-expect-error Runtime-frozen scenario fields must also be readonly in the public declaration.
scenario.revision = 2
// @ts-expect-error Nested scenario arrays must also be readonly in the public declaration.
scenario.oauth.authorizationScopes.push("unexpected")
}
void compileTimeScenarioReadonly
function compileTimeCatalogReadonly(profile: ProviderProfile, fault: FaultDefinition): void {
// @ts-expect-error Runtime-frozen provider profiles must also be readonly in the public declaration.
profile.displayName = "changed"
// @ts-expect-error Nested profile tools must also be readonly in the public declaration.
profile.tools.push(profile.tools[0])
// @ts-expect-error Runtime-frozen fault definitions must also be readonly in the public declaration.
fault.category = "changed"
}
void compileTimeCatalogReadonly
test("provider profiles are declarative, unique, and provenance-labelled", () => {
const profiles = listProviderProfiles()
assert.equal(Object.isFrozen(profiles), true)
assert.equal(profiles.length, 6)
assert.equal(new Set(profiles.map((profile) => profile.id)).size, profiles.length)
for (const profile of profiles) {
assert.equal(getProviderProfile(profile.id), profile)
assert.equal(Object.isFrozen(profile), true)
assert.equal(Object.isFrozen(profile.provenance), true)
assert.equal(Object.isFrozen(profile.tools), true)
assert.equal(Object.isFrozen(profile.tools[0]?.inputSchema), true)
assert.equal(profile.fixtureVersion, "2026-07-12.1")
assert.ok(profile.provenance.documentationUrls.length > 0)
assert.ok(profile.provenance.limitations.length > 0)
assert.ok(profile.oauth.requiredResourceScopes.every((scope) => profile.oauth.authorizationScopes.includes(scope)))
assert.equal(new Set(profile.tools.map((tool) => tool.name)).size, profile.tools.length)
assert.equal(profile.provenance.aspectFidelity.providerResults === "provider-documented", false)
if (profile.provider !== "synthetic") assert.equal(profile.provenance.aspectFidelity.authorization, "synthetic")
}
const serviceNow = profiles.find((profile) => profile.id === "servicenow-inbound-quickstart")
assert.ok(serviceNow)
assert.deepEqual(serviceNow.oauth.registrationModes, ["manual"])
assert.deepEqual(serviceNow.oauth.authorizationScopes, ["mcp_server"])
assert.equal(serviceNow.oauth.authorizationPath, "/oauth_auth.do")
assert.equal(serviceNow.oauth.tokenPath, "/oauth_token.do")
assert.equal(serviceNow.oauth.revocationPath, "/oauth_revoke.do")
assert.equal(serviceNow.provenance.aspectFidelity.catalog, "synthetic")
const workIq = profiles.find((profile) => profile.id === "microsoft-work-iq")
assert.ok(workIq)
assert.equal(workIq.canonicalEndpoint, "https://workiq.svc.cloud.microsoft/mcp")
assert.ok(workIq.oauth.authorizationScopes.includes("api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask"))
assert.ok(!workIq.oauth.requiredResourceScopes.includes("offline_access"))
assert.equal(workIq.provenance.aspectFidelity.toolSchemas, "synthetic")
assert.equal(workIq.provenance.aspectFidelity.providerResults, "synthetic")
const documentedWorkIqInputs: Readonly<Record<string, readonly string[]>> = {
fetch: ["agentId", "entityUrls"],
create_entity: ["agentId", "approved", "idempotency_key", "jsonBody", "parentUrl"],
update_entity: ["agentId", "approved", "entityUrl", "idempotency_key", "jsonBody"],
delete_entity: ["agentId", "approved", "entityUrl", "idempotency_key"],
do_action: ["actionUrl", "agentId", "approved", "idempotency_key", "jsonBody"],
call_function: ["agentId", "functionUrl"],
ask: ["agentId", "conversationId", "fileUrls", "question", "timeZone"],
list_agents: [],
get_schema: ["agentId", "backend", "format", "operationIds", "operationType", "path"],
search_paths: ["agentId", "backend", "filter"],
}
for (const [toolName, propertyNames] of Object.entries(documentedWorkIqInputs)) {
const matchingTool: MockTool | undefined = workIq.tools.find((candidate) => candidate.name === toolName)
assert.ok(matchingTool, `Missing Work IQ tool ${toolName}`)
assert.deepEqual(Object.keys(matchingTool.inputSchema.properties).sort(), [...propertyNames].sort())
}
assert.deepEqual(workIq.tools.find((tool) => tool.name === "fetch")?.inputSchema.required, ["entityUrls"])
assert.deepEqual(workIq.tools.find((tool) => tool.name === "list_agents")?.inputSchema.required, [])
assert.deepEqual(workIq.tools.find((tool) => tool.name === "get_schema")?.inputSchema.required, ["path", "operationType"])
assert.deepEqual(workIq.tools.find((tool) => tool.name === "search_paths")?.inputSchema.required, ["filter"])
const enterprise = profiles.find((profile) => profile.id === "microsoft-enterprise")
assert.ok(enterprise)
assert.equal(enterprise.canonicalEndpoint, "https://mcp.svc.cloud.microsoft/enterprise")
assert.equal(enterprise.endpointPath, "/enterprise")
assert.equal(enterprise.oauth.resource, "api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4")
assert.equal(enterprise.oauth.audience, "api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4")
assert.deepEqual(enterprise.oauth.authorizationScopes, ["api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4/.default"])
assert.equal(enterprise.oauth.authorizationPath, "/organizations/oauth2/v2.0/authorize")
assert.equal(enterprise.oauth.tokenPath, "/organizations/oauth2/v2.0/token")
assert.equal(enterprise.oauth.defaultClientAuthenticationMethod, "client_secret_post")
assert.equal(enterprise.provenance.aspectFidelity.toolSchemas, "synthetic")
const mail = profiles.find((profile) => profile.id === "agent-365-mail-v1-2026-07")
assert.ok(mail)
assert.equal(mail.tools.length, 10)
assert.equal(mail.tools[0]?.name, "mcp_MailTools_graph_mail_createMessage")
assert.equal(mail.provenance.aspectFidelity.catalog, "provider-documented")
assert.equal(mail.provenance.aspectFidelity.toolSchemas, "synthetic")
const slack = profiles.find((profile) => profile.id === "slack-user-mcp")
assert.ok(slack)
assert.equal(slack.oauth.registrationPath, null)
assert.equal(slack.oauth.defaultClientAuthenticationMethod, "client_secret_post")
assert.equal(slack.oauth.tokenResponseStyle, "slack-user")
assert.deepEqual(slack.protocol.versions, ["2025-06-18"])
assert.equal(slack.protocol.versionNegotiation, "strict")
})
test("Work IQ schemas accept current documented inputs and reject the old generic path mapper", () => {
const profile = getProviderProfile("microsoft-work-iq")
const schema = (toolName: string): MockTool["inputSchema"] => {
const tool: MockTool | undefined = profile.tools.find((candidate) => candidate.name === toolName)
assert.ok(tool, `Missing Work IQ tool ${toolName}`)
return tool.inputSchema
}
assert.equal(validateToolArguments(schema("fetch"), { entityUrls: ["/me/messages"] }).success, true)
assert.equal(validateToolArguments(schema("fetch"), { path: "/me/messages" }).success, false)
assert.equal(
validateToolArguments(schema("create_entity"), {
parentUrl: "/me/messages",
jsonBody: "{\"subject\":\"Synthetic\"}",
approved: true,
idempotency_key: "work-iq-create-1",
}).success,
true,
)
assert.equal(validateToolArguments(schema("call_function"), { functionUrl: "/me/calendarView" }).success, true)
assert.equal(validateToolArguments(schema("list_agents"), {}).success, true)
assert.equal(validateToolArguments(schema("list_agents"), { query: "old invented input" }).success, false)
assert.equal(
validateToolArguments(schema("get_schema"), { path: "/me/messages", operationType: "fetch", format: "jsonschema" }).success,
true,
)
assert.equal(validateToolArguments(schema("get_schema"), { operationType: "fetch" }).success, false)
assert.equal(validateToolArguments(schema("get_schema"), { path: "/me/messages", operationType: "delete" }).success, false)
assert.equal(validateToolArguments(schema("search_paths"), { filter: ".*calendar.*" }).success, true)
})
test("fault definitions are named, phase-specific, applicable, and scenario-bound", () => {
const faults = listFaultDefinitions()
assert.equal(faults.length, 32)
assert.equal(new Set(faults.map((fault) => fault.id)).size, faults.length)
for (const fault of faults) {
assert.ok(fault.phase)
assert.ok(fault.category)
assert.ok(fault.operatorAction)
const scenario = createFaultScenario(fault.applicableProfiles[0] ?? "synthetic-enterprise-oauth-mcp", fault.id)
assert.equal(scenario.expected.firstFailedPhase, fault.phase)
assert.equal(scenario.expected.category, fault.category)
}
const dcrFault = faults.find((fault) => fault.id === "oauth-dynamic-registration-unsupported")
assert.deepEqual(dcrFault?.applicableProfiles, ["synthetic-enterprise-oauth-mcp"])
})
test("redirect URI policy accepts HTTPS plus Azure-compatible localhost and literal loopback HTTP", () => {
assert.equal(isSafeOAuthRedirectUri("https://app.example.com/oauth/callback"), true)
assert.equal(isSafeOAuthRedirectUri("http://127.0.0.1:19876/mcp/oauth/callback"), true)
assert.equal(isSafeOAuthRedirectUri("http://[::1]:19876/mcp/oauth/callback"), true)
assert.equal(isSafeOAuthRedirectUri("http://localhost:19876/callback"), true)
assert.equal(isSafeOAuthRedirectUri("http://localhost.example.com:19876/callback"), false)
assert.equal(isSafeOAuthRedirectUri("http://127.0.0.1.example.com/callback"), false)
assert.equal(isSafeOAuthRedirectUri("javascript:alert(1)"), false)
assert.equal(isSafeOAuthRedirectUri("https://user:password@app.example.com/callback"), false)
assert.equal(isSafeOAuthRedirectUri("https://app.example.com/callback#token"), false)
const base = createDefaultScenario()
assert.equal(
scenarioSchema.safeParse({ ...base, oauth: { ...base.oauth, redirectUris: ["http://localhost:19876/callback"] } }).success,
true,
)
})
test("scenario pins provider fixture, required resource scopes, and supported session behavior", () => {
const base = createDefaultScenario("microsoft-work-iq")
assert.equal(scenarioSchema.safeParse({ ...base, profileFixtureVersion: "2026-07-12.999" }).success, false)
assert.equal(
scenarioSchema.safeParse({ ...base, oauth: { ...base.oauth, requiredResourceScopes: ["offline_access"] } }).success,
false,
)
assert.equal(scenarioSchema.safeParse({ ...base, protocol: { ...base.protocol, requireSession: false } }).success, false)
})
test("bounded tool schemas support nested enterprise payloads and reject hostile schema keys", () => {
const schema = toolInputSchemaSchema.parse({
type: "object",
properties: {
message: {
type: "object",
properties: {
recipients: {
type: "array",
items: {
type: "object",
properties: { address: { type: "string", minLength: 3, maxLength: 320 } },
required: ["address"],
additionalProperties: false,
},
minItems: 1,
maxItems: 20,
},
body: { oneOf: [{ type: "string", maxLength: 10_000 }, { type: "null" }] },
},
required: ["recipients", "body"],
additionalProperties: false,
},
},
required: ["message"],
additionalProperties: false,
})
assert.equal(validateToolArguments(schema, {
message: { recipients: [{ address: "person@example.invalid" }], body: "hello" },
}).success, true)
assert.equal(validateToolArguments(schema, {
message: { recipients: [{ address: "x" }], body: 42 },
}).success, false)
assert.equal(toolInputSchemaSchema.safeParse({
type: "object",
properties: { constructor: { type: "__proto__" } },
required: ["constructor"],
additionalProperties: false,
}).success, false)
})
@@ -0,0 +1,123 @@
import assert from "node:assert/strict"
import test from "node:test"
import {
createEnterpriseMcpMockServer,
createFaultScenario,
listFaultDefinitions,
probeEnterpriseMcpMockServer,
scenarioSchema,
} from "../src/index.js"
const oauthClientSecret = "synthetic-test-client-secret-32-bytes"
const hostileGatewayCases = [
{ faultId: "redirect-uri-whitelist", snippet: "redirect URI is not an allowed destination" },
{ faultId: "per-connector-redirect", snippet: "External MCP connect callback token exchange failed" },
{ faultId: "dcr-required", snippet: "The MCP connection failed before OpenWork could complete the protocol lifecycle" },
{ faultId: "method-405", snippet: "HTTP 405" },
{ faultId: "duplicate-amplification", snippet: "duplicate requests" },
{ faultId: "refresh-expired", snippet: "refresh token expired" },
{ faultId: "trailing-dot-url", snippet: "trailing-dot URL" },
{ faultId: "per-user-403", snippet: "Authorization with MCP server failed — check your credentials and permissions" },
]
test("hostile gateway fault catalog advertises every required selectable case", () => {
const faultIds = new Set(listFaultDefinitions().map((fault) => fault.id))
assert.deepEqual(hostileGatewayCases.map((fault) => fault.faultId).filter((faultId) => !faultIds.has(faultId)), [])
})
test("hostile gateway probes preserve the required safe evidence strings", async (context) => {
for (const { faultId, snippet } of hostileGatewayCases) {
await context.test(faultId, async () => {
const scenario = createFaultScenario("servicenow-inbound-quickstart", faultId)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const result = await probeEnterpriseMcpMockServer({
baseUrl: server.baseUrl,
scenario,
credentials: { clientSecret: oauthClientSecret },
})
assert.equal(result.ok, true, result.error?.messageSafe)
assert.match(result.error?.messageSafe ?? "", new RegExp(snippet.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")))
} finally {
await server.stop()
}
})
}
})
test("every advertised fault is observed at its actual first phase and leaves bounded state", async (context) => {
for (const fault of listFaultDefinitions()) {
for (const profileId of fault.applicableProfiles) {
await context.test(`${fault.id} / ${profileId}`, async () => {
const scenario = createFaultScenario(profileId, fault.id)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const result = await probeEnterpriseMcpMockServer({
baseUrl: server.baseUrl,
scenario,
credentials: { clientSecret: oauthClientSecret },
})
assert.equal(result.ok, true, `${fault.id} / ${profileId}: ${result.error?.messageSafe ?? "unexpected success"}`)
assert.equal(result.observed.outcome, "failure")
assert.equal(result.observed.firstFailedPhase, fault.phase)
assert.equal(result.observed.category, fault.category)
assert.equal(server.snapshot().counts.sessions, 0)
const events = server.events()
const appliedIndex = events.findIndex((event) => event.kind === "fault" && event.details.faultId === fault.id)
assert.notEqual(appliedIndex, -1, `${fault.id} did not emit its safe fault event`)
assert.equal(
events.slice(appliedIndex + 1).some((event) => event.phase === fault.phase && event.outcome === "passed"),
false,
`${fault.id} emitted a contradictory passed event after the fault was applied`,
)
} finally {
await server.stop()
}
})
}
}
})
test("probe cannot pass by copying expected fault metadata", async () => {
const serverScenario = createFaultScenario("synthetic-enterprise-oauth-mcp", "mcp-wrong-content-type")
const claimedScenario = createFaultScenario("synthetic-enterprise-oauth-mcp", "mcp-version-unsupported")
const server = createEnterpriseMcpMockServer({ scenario: serverScenario, secrets: { oauthClientSecret } })
await server.start()
try {
const result = await probeEnterpriseMcpMockServer({ baseUrl: server.baseUrl, scenario: claimedScenario })
assert.equal(result.ok, false)
assert.equal(result.observed.firstFailedPhase, "MCP_TRANSPORT")
assert.equal(result.observed.category, "mcp_transport")
assert.notEqual(result.observed.firstFailedPhase, claimedScenario.expected.firstFailedPhase)
} finally {
await server.stop()
}
})
test("probe refuses non-loopback targets before sending any request", async () => {
const scenario = createFaultScenario("synthetic-enterprise-oauth-mcp", "mcp-version-unsupported")
await assert.rejects(
probeEnterpriseMcpMockServer({ baseUrl: "https://example.com", scenario }),
/literal loopback/,
)
})
test("once-triggered cursor and duplicate faults are consumed only when their effect is reachable", async () => {
for (const faultId of ["mcp-catalog-cursor-loop", "mcp-duplicate-tool"] as const) {
const base = createFaultScenario("synthetic-enterprise-oauth-mcp", faultId)
const scenario = scenarioSchema.parse({
...base,
activeFault: { id: faultId, trigger: { occurrence: "once" } },
})
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const result = await probeEnterpriseMcpMockServer({ baseUrl: server.baseUrl, scenario })
assert.equal(result.ok, true, `${faultId}: ${result.error?.messageSafe ?? "unexpected success"}`)
} finally {
await server.stop()
}
}
})
@@ -0,0 +1,180 @@
import assert from "node:assert/strict"
import test from "node:test"
import { z } from "zod"
import {
createDefaultScenario,
createEnterpriseMcpMockServer,
createFaultScenario,
probeEnterpriseMcpMockServer,
scenarioSchema,
} from "../src/index.js"
import { authorizeManual, callRpc, initializeSession, sessionHeaders } from "./wire-client.js"
const oauthClientSecret = "synthetic-test-client-secret-32-bytes"
const toolResultSchema = z.object({
isError: z.boolean(),
structuredContent: z.unknown().optional(),
})
const toolErrorSchema = z.object({
error: z.object({ code: z.string() }),
})
test("mutations require approval and enforce idempotent duplicate versus conflicting arguments", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, token)
const denied = await callRpc(server.baseUrl, scenario, session, 10, "tools/call", {
name: "create_incident",
arguments: {
short_description: "Synthetic denied mutation",
idempotency_key: "mutation-key-denied",
approved: false,
},
})
const deniedResult = toolResultSchema.parse(denied.envelope.result)
assert.equal(deniedResult.isError, true)
assert.equal(toolErrorSchema.parse(deniedResult.structuredContent).error.code, "MOCK_APPROVAL_REQUIRED")
const argumentsValue = {
short_description: "Synthetic approved mutation",
idempotency_key: "mutation-key-approved",
approved: true,
}
const first = await callRpc(server.baseUrl, scenario, session, 11, "tools/call", {
name: "create_incident",
arguments: argumentsValue,
})
assert.equal(toolResultSchema.parse(first.envelope.result).isError, false)
assert.equal(server.snapshot().counts.operations, 1)
const duplicate = await callRpc(server.baseUrl, scenario, session, 12, "tools/call", {
name: "create_incident",
arguments: argumentsValue,
})
assert.equal(toolResultSchema.parse(duplicate.envelope.result).isError, false)
assert.equal(server.snapshot().counts.operations, 1)
const reorderedDuplicate = await callRpc(server.baseUrl, scenario, session, 14, "tools/call", {
name: "create_incident",
arguments: {
approved: true,
idempotency_key: "mutation-key-approved",
short_description: "Synthetic approved mutation",
},
})
assert.equal(toolResultSchema.parse(reorderedDuplicate.envelope.result).isError, false)
assert.equal(server.snapshot().counts.operations, 1)
const conflict = await callRpc(server.baseUrl, scenario, session, 13, "tools/call", {
name: "create_incident",
arguments: { ...argumentsValue, short_description: "Different mutation with reused key" },
})
const conflictResult = toolResultSchema.parse(conflict.envelope.result)
assert.equal(conflictResult.isError, true)
assert.equal(toolErrorSchema.parse(conflictResult.structuredContent).error.code, "IDEMPOTENCY_CONFLICT")
assert.equal(server.snapshot().counts.operations, 1)
} finally {
await server.stop()
}
})
test("timeout after commit remains indeterminate and requires reconciliation before replay", async () => {
const base = createFaultScenario("servicenow-inbound-quickstart", "mutation-timeout-after-commit")
const scenario = scenarioSchema.parse({
...base,
activeFault: { id: "mutation-timeout-after-commit", trigger: { occurrence: "once" } },
})
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, token)
const params = {
name: "create_incident",
arguments: {
short_description: "Synthetic indeterminate mutation",
idempotency_key: "mutation-key-indeterminate",
approved: true,
},
}
await assert.rejects(
fetch(server.mcpUrl, {
method: "POST",
headers: sessionHeaders(server.baseUrl, token.accessToken, session.sessionId, session.protocolVersion),
body: JSON.stringify({ jsonrpc: "2.0", id: 20, method: "tools/call", params }),
}),
)
assert.equal(server.snapshot().operations[0]?.state, "indeterminate")
const replay = await callRpc(server.baseUrl, scenario, session, 21, "tools/call", params)
const replayResult = toolResultSchema.parse(replay.envelope.result)
assert.equal(replayResult.isError, true)
assert.equal(toolErrorSchema.parse(replayResult.structuredContent).error.code, "MUTATION_RECONCILIATION_REQUIRED")
assert.equal(server.snapshot().operations[0]?.state, "indeterminate")
await server.stop()
assert.equal(server.snapshot().operations[0]?.state, "indeterminate")
await server.start()
const restartedToken = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const restartedSession = await initializeSession(server.baseUrl, scenario, restartedToken)
const replayAfterRestart = await callRpc(server.baseUrl, scenario, restartedSession, 22, "tools/call", params)
const restartedResult = toolResultSchema.parse(replayAfterRestart.envelope.result)
assert.equal(restartedResult.isError, true)
assert.equal(toolErrorSchema.parse(restartedResult.structuredContent).error.code, "MUTATION_RECONCILIATION_REQUIRED")
} finally {
await server.stop()
}
})
test("local mutation approval fails before a configured provider fault can be emitted", async () => {
const scenario = createFaultScenario("servicenow-inbound-quickstart", "provider-authorization-denied")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, token)
const denied = await callRpc(server.baseUrl, scenario, session, 50, "tools/call", {
name: "create_incident",
arguments: {
short_description: "Must not reach provider",
idempotency_key: "local-approval-first",
approved: false,
},
})
const result = toolResultSchema.parse(denied.envelope.result)
assert.equal(toolErrorSchema.parse(result.structuredContent).error.code, "MOCK_APPROVAL_REQUIRED")
assert.equal(server.events().some((event) => event.kind === "fault"), false)
} finally {
await server.stop()
}
})
test("safe-read probe mode rejects an explicit mutation override before any operation is prepared", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const result = await probeEnterpriseMcpMockServer({
baseUrl: server.baseUrl,
scenario,
credentials: { clientSecret: oauthClientSecret },
mode: "safe-read",
callTool: {
name: "create_incident",
arguments: {
short_description: "Must remain uncommitted",
idempotency_key: "safe-read-mutation-rejected",
approved: true,
},
},
})
assert.equal(result.ok, false)
assert.equal(result.error?.phase, "CONFIGURATION")
assert.equal(server.snapshot().counts.operations, 0)
} finally {
await server.stop()
}
})
@@ -0,0 +1,391 @@
import assert from "node:assert/strict"
import test from "node:test"
import { createHash } from "node:crypto"
import { z } from "zod"
import {
createDefaultScenario,
createEnterpriseMcpMockServer,
getProviderProfile,
} from "../src/index.js"
import type { ProviderProfileId } from "../src/index.js"
import { authorizeClient, authorizeManual, callRpc, initializeSession, rpcHeaders } from "./wire-client.js"
const oauthClientSecret = "synthetic-test-client-secret-32-bytes"
async function invalidClientTokenResponse(profileId: ProviderProfileId): Promise<Response> {
const scenario = createDefaultScenario(profileId)
const profile = getProviderProfile(profileId)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const verifier = "wire-test-pkce-verifier-with-more-than-43-characters-1234567890"
const challenge = createHash("sha256").update(verifier).digest("base64url")
const redirectUri = scenario.oauth.redirectUris[0]
assert.ok(redirectUri)
const authorize = new URL(profile.oauth.authorizationPath, server.baseUrl)
authorize.searchParams.set("response_type", "code")
authorize.searchParams.set("client_id", scenario.oauth.clientId)
authorize.searchParams.set("redirect_uri", redirectUri)
authorize.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
authorize.searchParams.set("resource", server.mcpUrl)
authorize.searchParams.set("state", "invalid-client-state")
authorize.searchParams.set("code_challenge", challenge)
authorize.searchParams.set("code_challenge_method", "S256")
const authorizeResponse = await fetch(authorize, { redirect: "manual" })
assert.equal(authorizeResponse.status, 302)
const location = authorizeResponse.headers.get("location")
assert.ok(location)
const code = new URL(location).searchParams.get("code")
assert.ok(code)
return await fetch(new URL(profile.oauth.tokenPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: scenario.oauth.clientId,
client_secret: "wrong-secret-must-not-be-echoed",
redirect_uri: redirectUri,
code,
code_verifier: verifier,
resource: server.mcpUrl,
}),
})
} finally {
await server.stop()
}
}
test("ServiceNow profile exposes exact manual OAuth topology and enforces exact redirects", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const profile = getProviderProfile(scenario.profileId)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const metadataResponse = await fetch(new URL("/.well-known/oauth-authorization-server", server.baseUrl))
const metadataText = await metadataResponse.text()
const metadataValue: unknown = JSON.parse(metadataText)
const metadata = z.object({
authorization_endpoint: z.url(),
token_endpoint: z.url(),
revocation_endpoint: z.url(),
registration_endpoint: z.unknown().optional(),
}).parse(metadataValue)
assert.equal(new URL(metadata.authorization_endpoint).pathname, "/oauth_auth.do")
assert.equal(new URL(metadata.token_endpoint).pathname, "/oauth_token.do")
assert.equal(new URL(metadata.revocation_endpoint).pathname, "/oauth_revoke.do")
assert.equal(metadata.registration_endpoint, undefined)
const invalidRedirect = new URL(profile.oauth.authorizationPath, server.baseUrl)
invalidRedirect.searchParams.set("response_type", "code")
invalidRedirect.searchParams.set("client_id", scenario.oauth.clientId)
invalidRedirect.searchParams.set("redirect_uri", "https://attacker.example/callback")
invalidRedirect.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
invalidRedirect.searchParams.set("resource", server.mcpUrl)
invalidRedirect.searchParams.set("state", "state")
invalidRedirect.searchParams.set("code_challenge", "challenge")
invalidRedirect.searchParams.set("code_challenge_method", "S256")
const invalidRedirectResponse = await fetch(invalidRedirect, { redirect: "manual" })
assert.equal(invalidRedirectResponse.status, 400)
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
assert.match(token.accessToken, /^access-token-/)
} finally {
await server.stop()
}
})
test("Microsoft and ServiceNow retain distinct safe invalid-client evidence", async () => {
const microsoftResponse = await invalidClientTokenResponse("microsoft-enterprise")
assert.equal(microsoftResponse.status, 401)
const microsoftValue: unknown = JSON.parse(await microsoftResponse.text())
const microsoftError = z.object({
error: z.literal("invalid_client"),
error_description: z.string(),
error_codes: z.tuple([z.literal(7_000_215)]),
timestamp: z.string(),
trace_id: z.string().uuid(),
correlation_id: z.string().uuid(),
}).parse(microsoftValue)
assert.match(microsoftError.error_description, /AADSTS7000215/)
assert.match(microsoftError.error_description, /client secret value, not the client secret ID/)
assert.doesNotMatch(microsoftError.error_description, /wrong-secret-must-not-be-echoed/)
const serviceNowResponse = await invalidClientTokenResponse("servicenow-inbound-quickstart")
assert.equal(serviceNowResponse.status, 401)
const serviceNowValue: unknown = JSON.parse(await serviceNowResponse.text())
const serviceNowError = z.object({
error: z.literal("invalid_client"),
error_description: z.string(),
}).strict().parse(serviceNowValue)
assert.match(serviceNowError.error_description, /ServiceNow OAuth application/)
assert.match(serviceNowError.error_description, /client ID and client secret/)
assert.doesNotMatch(serviceNowError.error_description, /wrong-secret-must-not-be-echoed/)
assert.doesNotMatch(serviceNowError.error_description, /AADSTS/)
})
test("dynamic registration retains none and client_secret_post authentication methods", async () => {
const scenario = createDefaultScenario("synthetic-enterprise-oauth-mcp")
const profile = getProviderProfile(scenario.profileId)
const registrationPath = profile.oauth.registrationPath
assert.ok(registrationPath)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const noneRegistration = await fetch(new URL(registrationPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ redirect_uris: scenario.oauth.redirectUris, token_endpoint_auth_method: "none" }),
})
assert.equal(noneRegistration.status, 201)
const noneValue: unknown = JSON.parse(await noneRegistration.text())
const noneClient = z.object({ client_id: z.string(), token_endpoint_auth_method: z.literal("none") }).parse(noneValue)
const noneToken = await authorizeClient(server.baseUrl, scenario, noneClient.client_id)
assert.ok(noneToken.accessToken)
const secretRegistration = await fetch(new URL(registrationPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ redirect_uris: scenario.oauth.redirectUris, token_endpoint_auth_method: "client_secret_post" }),
})
assert.equal(secretRegistration.status, 201)
const secretValue: unknown = JSON.parse(await secretRegistration.text())
const secretClient = z.object({
client_id: z.string(),
client_secret: z.string(),
token_endpoint_auth_method: z.literal("client_secret_post"),
}).parse(secretValue)
const secretToken = await authorizeClient(server.baseUrl, scenario, secretClient.client_id, secretClient.client_secret)
assert.ok(secretToken.accessToken)
await assert.rejects(authorizeClient(server.baseUrl, scenario, secretClient.client_id), /Token exchange failed with 401/)
} finally {
await server.stop()
}
})
test("refresh rotates tokens and revocation invalidates the active access token", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const profile = getProviderProfile(scenario.profileId)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const first = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const refreshForm = new URLSearchParams({
grant_type: "refresh_token",
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
refresh_token: first.refreshToken,
})
const refreshResponse = await fetch(new URL(profile.oauth.tokenPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: refreshForm,
})
assert.equal(refreshResponse.status, 200)
const refreshedValue: unknown = JSON.parse(await refreshResponse.text())
const refreshed = z.object({ access_token: z.string(), refresh_token: z.string() }).parse(refreshedValue)
assert.notEqual(refreshed.access_token, first.accessToken)
assert.notEqual(refreshed.refresh_token, first.refreshToken)
const replayResponse = await fetch(new URL(profile.oauth.tokenPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: refreshForm,
})
assert.equal(replayResponse.status, 400)
const revokeResponse = await fetch(new URL(profile.oauth.revocationPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
token: refreshed.access_token,
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
}),
})
assert.equal(revokeResponse.status, 200)
const protectedResponse = await fetch(server.mcpUrl, {
method: "POST",
headers: {
authorization: `Bearer ${refreshed.access_token}`,
accept: "application/json, text/event-stream",
"content-type": "application/json",
origin: new URL(server.baseUrl).origin,
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
})
assert.equal(protectedResponse.status, 401)
} finally {
await server.stop()
}
})
test("authorization codes bind exact PKCE verifier and become unusable after one exchange", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const profile = getProviderProfile(scenario.profileId)
const redirectUri = scenario.oauth.redirectUris[0]
assert.ok(redirectUri)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const verifier = "wire-test-pkce-verifier-with-more-than-43-characters-1234567890"
const challenge = createHash("sha256").update(verifier).digest("base64url")
const authorizeUrl = new URL(profile.oauth.authorizationPath, server.baseUrl)
authorizeUrl.searchParams.set("response_type", "code")
authorizeUrl.searchParams.set("client_id", scenario.oauth.clientId)
authorizeUrl.searchParams.set("redirect_uri", redirectUri)
authorizeUrl.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
authorizeUrl.searchParams.set("resource", server.mcpUrl)
authorizeUrl.searchParams.set("state", "one-time-state")
authorizeUrl.searchParams.set("code_challenge", challenge)
authorizeUrl.searchParams.set("code_challenge_method", "S256")
const authorizeResponse = await fetch(authorizeUrl, { redirect: "manual" })
const location = authorizeResponse.headers.get("location")
assert.ok(location)
const code = new URL(location).searchParams.get("code")
assert.ok(code)
const tokenRequest = (codeVerifier: string): Promise<Response> =>
fetch(new URL(profile.oauth.tokenPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
redirect_uri: redirectUri,
resource: server.mcpUrl,
code,
code_verifier: codeVerifier,
}),
})
assert.equal((await tokenRequest("wrong-verifier")).status, 400)
assert.equal((await tokenRequest(verifier)).status, 200)
assert.equal((await tokenRequest(verifier)).status, 400)
} finally {
await server.stop()
}
})
test("authorization rejects unsupported response types and malformed PKCE challenges", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const profile = getProviderProfile(scenario.profileId)
const redirectUri = scenario.oauth.redirectUris[0]
assert.ok(redirectUri)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const authorize = (responseType: string, challenge: string): Promise<Response> => {
const url = new URL(profile.oauth.authorizationPath, server.baseUrl)
url.searchParams.set("response_type", responseType)
url.searchParams.set("client_id", scenario.oauth.clientId)
url.searchParams.set("redirect_uri", redirectUri)
url.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
url.searchParams.set("resource", server.mcpUrl)
url.searchParams.set("state", "state")
url.searchParams.set("code_challenge", challenge)
url.searchParams.set("code_challenge_method", "S256")
return fetch(url, { redirect: "manual" })
}
assert.equal((await authorize("token", "A".repeat(43))).status, 400)
assert.equal((await authorize("code", "short")).status, 400)
} finally {
await server.stop()
}
})
test("refresh authority outlives access expiry and preserves only the original MCP session lineage", async () => {
let now = 1_700_000_000_000
let counter = 0
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const profile = getProviderProfile(scenario.profileId)
const server = createEnterpriseMcpMockServer({
scenario,
secrets: { oauthClientSecret },
environment: {
now: () => now,
randomId: () => `refresh-${++counter}`,
opaqueValue: (prefix) => `${prefix}-${++counter}`,
},
})
await server.start()
try {
const first = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, first)
now += 3_600_001
const refreshResponse = await fetch(new URL(profile.oauth.tokenPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
refresh_token: first.refreshToken,
}),
})
assert.equal(refreshResponse.status, 200)
const refreshed = z.object({ access_token: z.string(), refresh_token: z.string() }).parse(JSON.parse(await refreshResponse.text()))
const continued = await callRpc(
server.baseUrl,
scenario,
{ ...session, accessToken: refreshed.access_token, refreshToken: refreshed.refresh_token },
44,
"tools/list",
{},
)
assert.equal(continued.envelope.error, undefined)
const expiredAccess = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, first.accessToken),
body: JSON.stringify({ jsonrpc: "2.0", id: 45, method: "initialize", params: {} }),
})
assert.equal(expiredAccess.status, 401)
} finally {
await server.stop()
}
})
test("one dynamic OAuth client cannot revoke another client's token", async () => {
const scenario = createDefaultScenario("synthetic-enterprise-oauth-mcp")
const profile = getProviderProfile(scenario.profileId)
assert.ok(profile.oauth.registrationPath)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret: "" } })
await server.start()
try {
const register = async (): Promise<string> => {
const response = await fetch(new URL(profile.oauth.registrationPath ?? "", server.baseUrl), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ redirect_uris: scenario.oauth.redirectUris, token_endpoint_auth_method: "none" }),
})
return z.object({ client_id: z.string() }).parse(JSON.parse(await response.text())).client_id
}
const clientA = await register()
const clientB = await register()
const tokenA = await authorizeClient(server.baseUrl, scenario, clientA)
const denied = await fetch(new URL(profile.oauth.revocationPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token: tokenA.accessToken, client_id: clientB }),
})
assert.equal(denied.status, 401)
assert.equal((await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, tokenA.accessToken),
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: { protocolVersion: scenario.protocol.version, capabilities: {}, clientInfo: { name: "owner-check", version: "1" } },
}),
})).status, 200)
const allowed = await fetch(new URL(profile.oauth.revocationPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token: tokenA.accessToken, client_id: clientA }),
})
assert.equal(allowed.status, 200)
} finally {
await server.stop()
}
})
@@ -0,0 +1,139 @@
import assert from "node:assert/strict"
import test from "node:test"
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
import { createDefaultScenario, getProviderProfile, probeEnterpriseMcpMockServer } from "../src/index.js"
async function localServer(
handler: (request: IncomingMessage, response: ServerResponse, baseUrl: string) => void | Promise<void>,
): Promise<{ baseUrl: string; close(): Promise<void> }> {
let baseUrl = ""
const server = createServer((request, response) => {
void Promise.resolve(handler(request, response, baseUrl)).catch(() => response.destroy())
})
await new Promise<void>((resolve, reject) => {
server.once("error", reject)
server.listen(0, "127.0.0.1", () => resolve())
})
const address = server.address()
if (!address || typeof address === "string") throw new Error("Test server did not bind")
baseUrl = `http://127.0.0.1:${address.port}`
return {
baseUrl,
close: async () => {
server.closeAllConnections()
await new Promise<void>((resolve) => server.close(() => resolve()))
},
}
}
function challenge(response: ServerResponse, baseUrl: string, endpointPath: string): void {
response.writeHead(401, {
"content-type": "application/json",
"www-authenticate": `Bearer resource_metadata="${baseUrl}/.well-known/oauth-protected-resource${endpointPath}"`,
})
response.end('{"error":"unauthorized"}')
}
test("probe bounds oversized and stalled response bodies after headers", async () => {
const scenario = createDefaultScenario("synthetic-enterprise-oauth-mcp")
const profile = getProviderProfile(scenario.profileId)
const oversized = await localServer((request, response, baseUrl) => {
if (request.method === "POST" && request.url === profile.endpointPath) return challenge(response, baseUrl, profile.endpointPath)
response.writeHead(200, { "content-type": "application/json" })
response.end(JSON.stringify({ padding: "x".repeat(1024 * 1024 + 1) }))
})
try {
const result = await probeEnterpriseMcpMockServer({ baseUrl: oversized.baseUrl, scenario })
assert.equal(result.ok, false)
assert.match(result.error?.messageSafe ?? "", /exceeded the 1048576-byte probe limit/)
} finally {
await oversized.close()
}
const stalled = await localServer((request, response, baseUrl) => {
if (request.method === "POST" && request.url === profile.endpointPath) return challenge(response, baseUrl, profile.endpointPath)
response.writeHead(200, { "content-type": "application/json" })
response.write('{"resource":')
})
try {
const result = await probeEnterpriseMcpMockServer({ baseUrl: stalled.baseUrl, scenario, timeoutMs: 100 })
assert.equal(result.ok, false)
assert.match(result.error?.messageSafe ?? "", /timed out/)
} finally {
await stalled.close()
}
})
test("probe redacts a client secret echoed by a hostile local OAuth endpoint", async () => {
const secret = "echoed-client-secret-must-never-return"
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const profile = getProviderProfile(scenario.profileId)
const fake = await localServer(async (request, response, baseUrl) => {
const url = new URL(request.url ?? "/", baseUrl)
if (request.method === "POST" && url.pathname === profile.endpointPath) return challenge(response, baseUrl, profile.endpointPath)
if (url.pathname === `/.well-known/oauth-protected-resource${profile.endpointPath}`) {
response.writeHead(200, { "content-type": "application/json" })
response.end(JSON.stringify({
resource: `${baseUrl}${profile.endpointPath}`,
authorization_servers: [baseUrl],
scopes_supported: scenario.oauth.requiredResourceScopes,
}))
return
}
if (url.pathname === "/.well-known/oauth-authorization-server") {
response.writeHead(200, { "content-type": "application/json" })
response.end(JSON.stringify({
issuer: baseUrl,
authorization_endpoint: `${baseUrl}${profile.oauth.authorizationPath}`,
token_endpoint: `${baseUrl}${profile.oauth.tokenPath}`,
revocation_endpoint: `${baseUrl}${profile.oauth.revocationPath}`,
code_challenge_methods_supported: ["S256"],
}))
return
}
if (url.pathname === profile.oauth.authorizationPath) {
const destination = new URL(scenario.oauth.redirectUris[0] ?? "http://127.0.0.1/callback")
destination.searchParams.set("code", "synthetic-code")
destination.searchParams.set("state", url.searchParams.get("state") ?? "")
response.writeHead(302, { location: destination.href })
response.end()
return
}
if (url.pathname === profile.oauth.tokenPath) {
for await (const _chunk of request) {
// Consume the bounded request so the fake endpoint behaves like a real token endpoint.
}
response.writeHead(401, { "content-type": "application/json" })
response.end(JSON.stringify({ error: "invalid_client", error_description: `provider echoed ${secret}` }))
return
}
response.writeHead(404).end()
})
try {
const result = await probeEnterpriseMcpMockServer({
baseUrl: fake.baseUrl,
scenario,
credentials: { clientSecret: secret },
})
assert.equal(result.ok, false)
assert.equal(JSON.stringify(result).includes(secret), false)
assert.match(result.error?.messageSafe ?? "", /\[REDACTED\]/)
} finally {
await fake.close()
}
})
test("probe attributes a closed loopback port to TCP reachability, not HTTP routing", async () => {
const closed = await localServer((_request, response) => {
response.end()
})
const baseUrl = closed.baseUrl
await closed.close()
const scenario = createDefaultScenario("synthetic-enterprise-oauth-mcp")
const result = await probeEnterpriseMcpMockServer({ baseUrl, scenario, timeoutMs: 500 })
assert.equal(result.ok, false)
assert.equal(result.observed.firstFailedPhase, "NETWORK_TCP")
assert.equal(result.observed.category, "network_tcp")
assert.equal(result.error?.messageSafe.includes("HTTP routing"), false)
})
@@ -0,0 +1,329 @@
import assert from "node:assert/strict"
import test from "node:test"
import { z } from "zod"
import {
createDefaultScenario,
createEnterpriseMcpMockServer,
createFaultScenario,
getProviderProfile,
scenarioSchema,
toolInputSchemaSchema,
} from "../src/index.js"
import { authorizeManual, callRpc, initializeSession, rpcHeaders, sessionHeaders } from "./wire-client.js"
const oauthClientSecret = "synthetic-test-client-secret-32-bytes"
const errorEnvelopeSchema = z.object({ error: z.object({ code: z.number(), message: z.string() }) })
test("Origin is rejected before credentials and session binding prevents cross-token use or deletion", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const hostileOrigin = await fetch(server.mcpUrl, {
method: "POST",
headers: {
origin: "https://attacker.example",
accept: "application/json, text/event-stream",
"content-type": "application/json",
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
})
assert.equal(hostileOrigin.status, 403)
assert.equal(hostileOrigin.headers.get("www-authenticate"), null)
const firstToken = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const secondToken = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const firstSession = await initializeSession(server.baseUrl, scenario, firstToken)
const profile = getProviderProfile(scenario.profileId)
const hijackHeaders = sessionHeaders(
server.baseUrl,
secondToken.accessToken,
firstSession.sessionId,
firstSession.protocolVersion,
)
const hijack = await fetch(new URL(profile.endpointPath, server.baseUrl), {
method: "POST",
headers: hijackHeaders,
body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }),
})
assert.equal(hijack.status, 403)
const foreignDelete = await fetch(new URL(profile.endpointPath, server.baseUrl), {
method: "DELETE",
headers: hijackHeaders,
})
assert.equal(foreignDelete.status, 403)
assert.equal(server.snapshot().counts.sessions, 1)
const ownDelete = await fetch(new URL(profile.endpointPath, server.baseUrl), {
method: "DELETE",
headers: sessionHeaders(
server.baseUrl,
firstToken.accessToken,
firstSession.sessionId,
firstSession.protocolVersion,
),
})
assert.equal(ownDelete.status, 204)
assert.equal(server.snapshot().counts.sessions, 0)
} finally {
await server.stop()
}
})
test("transport, JSON-RPC, protocol, and session validation stay precisely shaped", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const profile = getProviderProfile(scenario.profileId)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const plainText = await fetch(server.mcpUrl, {
method: "POST",
headers: { ...rpcHeaders(server.baseUrl, token.accessToken), "content-type": "text/plain" },
body: "not json",
})
assert.equal(plainText.status, 415)
const jsonp = await fetch(server.mcpUrl, {
method: "POST",
headers: { ...rpcHeaders(server.baseUrl, token.accessToken), "content-type": "application/jsonp" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
})
assert.equal(jsonp.status, 415)
const malformed = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: "{",
})
assert.equal(malformed.status, 200)
const malformedValue: unknown = JSON.parse(await malformed.text())
assert.equal(errorEnvelopeSchema.parse(malformedValue).error.code, -32700)
const invalidRequest = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: JSON.stringify({ hello: "world" }),
})
const invalidValue: unknown = JSON.parse(await invalidRequest.text())
assert.equal(errorEnvelopeSchema.parse(invalidValue).error.code, -32600)
const missingAccept = await fetch(server.mcpUrl, {
method: "POST",
headers: {
authorization: `Bearer ${token.accessToken}`,
accept: "application/json",
"content-type": "application/json",
origin: new URL(server.baseUrl).origin,
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
})
assert.equal(missingAccept.status, 406)
const nearMatchAccept = await fetch(server.mcpUrl, {
method: "POST",
headers: {
authorization: `Bearer ${token.accessToken}`,
accept: "application/jsonp, text/event-streaming",
"content-type": "application/json",
origin: new URL(server.baseUrl).origin,
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
})
assert.equal(nearMatchAccept.status, 406)
const explicitlyRejectedRepresentations = await fetch(server.mcpUrl, {
method: "POST",
headers: {
authorization: `Bearer ${token.accessToken}`,
accept: "application/json;q=0, text/event-stream;q=0",
"content-type": "application/json",
origin: new URL(server.baseUrl).origin,
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
})
assert.equal(explicitlyRejectedRepresentations.status, 406)
const lowercaseBearer = await fetch(server.mcpUrl, {
method: "POST",
headers: { ...rpcHeaders(server.baseUrl, token.accessToken), authorization: `bearer ${token.accessToken}` },
body: JSON.stringify({
jsonrpc: "2.0",
id: 19,
method: "initialize",
params: { protocolVersion: scenario.protocol.version, capabilities: {}, clientInfo: { name: "wire-test", version: "1" } },
}),
})
assert.equal(lowercaseBearer.status, 200)
const missingCapabilities = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: JSON.stringify({
jsonrpc: "2.0",
id: 20,
method: "initialize",
params: { protocolVersion: "1900-01-01", clientInfo: { name: "wire-test", version: "1" } },
}),
})
assert.equal(errorEnvelopeSchema.parse(JSON.parse(await missingCapabilities.text())).error.code, -32602)
const downgraded = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: JSON.stringify({
jsonrpc: "2.0",
id: 21,
method: "initialize",
params: {
protocolVersion: "1900-01-01",
capabilities: {},
clientInfo: { name: "wire-test", version: "1" },
},
}),
})
const downgradedEnvelope = z.object({
result: z.object({ protocolVersion: z.string() }),
}).parse(JSON.parse(await downgraded.text()))
assert.equal(downgradedEnvelope.result.protocolVersion, scenario.protocol.version)
assert.equal(downgraded.headers.get("mcp-protocol-version"), scenario.protocol.version)
const session = await initializeSession(server.baseUrl, scenario, token)
const missingSession = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }),
})
assert.equal(missingSession.status, 400)
const wrongProtocol = await fetch(server.mcpUrl, {
method: "POST",
headers: {
...sessionHeaders(server.baseUrl, token.accessToken, session.sessionId, "1900-01-01"),
},
body: JSON.stringify({ jsonrpc: "2.0", id: 3, method: "tools/list", params: {} }),
})
assert.equal(wrongProtocol.status, 400)
const unknown = await callRpc(server.baseUrl, scenario, session, 4, "unknown/method", {})
assert.equal(unknown.envelope.error?.code, -32601)
const invalidArguments = await callRpc(server.baseUrl, scenario, session, 5, "tools/call", {
name: "get_incident",
arguments: { number: 42, extra: true },
})
assert.equal(invalidArguments.envelope.error?.code, -32602)
const initializedWithId = await fetch(server.mcpUrl, {
method: "POST",
headers: sessionHeaders(server.baseUrl, session.accessToken, session.sessionId, session.protocolVersion),
body: JSON.stringify({ jsonrpc: "2.0", id: 6, method: "notifications/initialized" }),
})
assert.equal(initializedWithId.status, 200)
assert.equal(errorEnvelopeSchema.parse(JSON.parse(await initializedWithId.text())).error.code, -32600)
const unknownNotification = await fetch(server.mcpUrl, {
method: "POST",
headers: sessionHeaders(server.baseUrl, session.accessToken, session.sessionId, session.protocolVersion),
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/synthetic-unknown" }),
})
assert.equal(unknownNotification.status, 202)
assert.equal(await unknownNotification.text(), "")
const clientResponse = await fetch(server.mcpUrl, {
method: "POST",
headers: sessionHeaders(server.baseUrl, session.accessToken, session.sessionId, session.protocolVersion),
body: JSON.stringify({ jsonrpc: "2.0", id: 91, result: { accepted: true } }),
})
assert.equal(clientResponse.status, 202)
assert.equal(await clientResponse.text(), "")
const badCursor = await callRpc(server.baseUrl, scenario, session, 7, "tools/list", { cursor: "page:1junk" })
assert.equal(badCursor.envelope.error?.code, -32602)
const oversized = "x".repeat(1024 * 1024 + 1)
const oversizedResponse = await fetch(new URL(profile.endpointPath, server.baseUrl), {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: oversized,
})
assert.equal(oversizedResponse.status, 413)
} finally {
await server.stop()
}
})
test("tool results mirror structured content for legacy clients and keep the synthetic profile vendor-neutral", async () => {
const base = createDefaultScenario("synthetic-enterprise-oauth-mcp")
const scenario = scenarioSchema.parse({ ...base, oauth: { ...base.oauth, registration: "manual" } })
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, token)
const call = await callRpc(server.baseUrl, scenario, session, 30, "tools/call", {
name: "search_records",
arguments: { query: "synthetic" },
})
const result = z.object({
isError: z.literal(false),
content: z.array(z.object({ type: z.literal("text"), text: z.string() })).min(1),
structuredContent: z.object({ provider: z.string() }).passthrough(),
}).parse(call.envelope.result)
assert.equal(result.structuredContent.provider, "synthetic")
assert.deepEqual(JSON.parse(result.content[0]?.text ?? ""), result.structuredContent)
} finally {
await server.stop()
}
})
test("invalid tool-schema fault is genuinely invalid JSON Schema on the wire", async () => {
const scenario = createFaultScenario("servicenow-inbound-quickstart", "mcp-invalid-tool-schema")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, token)
const list = await callRpc(server.baseUrl, scenario, session, 29, "tools/list", {})
const result = z.object({
tools: z.array(z.object({ inputSchema: z.unknown() }).passthrough()).min(1),
}).parse(list.envelope.result)
const inputSchema = z.object({
type: z.literal("object"),
required: z.string(),
}).passthrough().parse(result.tools[0]?.inputSchema)
assert.equal(inputSchema.required, "missing")
assert.equal(toolInputSchemaSchema.safeParse(inputSchema).success, false)
} finally {
await server.stop()
}
})
test("provider tool faults expose top-level Den-compatible evidence and a detailed nested error", async () => {
const scenario = createFaultScenario("servicenow-inbound-quickstart", "provider-authorization-denied")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, token)
const call = await callRpc(server.baseUrl, scenario, session, 31, "tools/call", {
name: "get_incident",
arguments: { number: "INC0000001" },
})
const result = z.object({
isError: z.literal(true),
content: z.array(z.object({ type: z.literal("text"), text: z.string() })).min(1),
structuredContent: z.object({
providerStatus: z.literal(403),
category: z.literal("provider_acl"),
requestId: z.string(),
error: z.object({ code: z.literal("PROVIDER_ACL_DENIED"), providerRequestId: z.string() }).passthrough(),
}).passthrough(),
}).parse(call.envelope.result)
assert.equal(result.structuredContent.requestId, result.structuredContent.error.providerRequestId)
assert.deepEqual(JSON.parse(result.content[0]?.text ?? ""), result.structuredContent)
} finally {
await server.stop()
}
})
@@ -0,0 +1,158 @@
import assert from "node:assert/strict"
import test from "node:test"
import {
createDefaultScenario,
createEnterpriseMcpMockServer,
probeEnterpriseMcpMockServer,
scenarioSchema,
ScenarioRevisionConflictError,
} from "../src/index.js"
const oauthClientSecret = "synthetic-test-client-secret-32-bytes"
test("healthy ServiceNow profile completes OAuth, MCP, pagination, and cleanup", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
const started = await server.start()
try {
assert.equal(started.status, "running")
assert.match(server.mcpUrl, /\/sncapps\/mcp-server\/mcp\/sn_mcp_server_default$/)
const result = await probeEnterpriseMcpMockServer({
baseUrl: server.baseUrl,
scenario,
credentials: { clientSecret: oauthClientSecret },
})
assert.equal(result.ok, true, result.error?.messageSafe)
assert.equal(result.observed.outcome, "success")
assert.equal(result.toolCount, 4)
assert.equal(server.snapshot().counts.sessions, 0)
assert.equal(server.snapshot().counts.tokens, 0)
const serializedEvents = JSON.stringify(server.events())
assert.equal(serializedEvents.includes(oauthClientSecret), false)
assert.equal(serializedEvents.includes("access-token-"), false)
assert.equal(serializedEvents.includes("refresh-token-"), false)
} finally {
const stopped = await server.stop()
assert.equal(stopped.status, "stopped")
assert.equal(stopped.counts.sessions, 0)
assert.equal(stopped.counts.tokens, 0)
}
})
test("SSE and dynamic client registration form a healthy spec-conformance profile", async () => {
const base = createDefaultScenario("synthetic-enterprise-oauth-mcp")
const scenario = scenarioSchema.parse({ ...base, protocol: { ...base.protocol, responseMode: "sse" } })
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const result = await probeEnterpriseMcpMockServer({ baseUrl: server.baseUrl, scenario })
assert.equal(result.ok, true, result.error?.messageSafe)
assert.equal(result.toolCount, 2)
assert.equal(server.snapshot().counts.sessions, 0)
} finally {
await server.stop()
}
})
test("controller serializes concurrent lifecycle calls and enforces revision CAS", async () => {
const scenario = createDefaultScenario()
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
const [first, second] = await Promise.all([server.start(), server.start()])
assert.equal(first.baseUrl, second.baseUrl)
assert.equal(first.instanceId, second.instanceId)
const next = scenarioSchema.parse({ ...scenario, id: "servicenow-revision-two", revision: 2 })
await assert.rejects(server.updateScenario(next, 99), ScenarioRevisionConflictError)
const updated = await server.updateScenario(next, 1)
assert.equal(updated.status, "running")
assert.equal(updated.scenario.revision, 2)
const [stoppedOnce, stoppedTwice] = await Promise.all([server.stop(), server.stop()])
assert.equal(stoppedOnce.status, "stopped")
assert.equal(stoppedTwice.status, "stopped")
assert.equal(stoppedTwice.counts.sessions, 0)
})
test("injected environment makes runtime identifiers and time deterministic", async () => {
let counter = 0
const environment = {
now: () => 1_700_000_000_000,
randomId: () => `uuid-${++counter}`,
opaqueValue: (prefix: string) => `${prefix}-value-${++counter}`,
}
const scenario = createDefaultScenario()
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret }, environment })
const started = await server.start()
try {
assert.equal(started.instanceId, "uuid-1")
assert.equal(server.events()[0]?.occurredAt, "2023-11-14T22:13:20.000Z")
} finally {
await server.stop()
}
})
test("data-plane health is minimal and contains no scenario or secret material", async () => {
const scenario = createDefaultScenario()
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const response = await fetch(new URL("/health", server.baseUrl))
const text = await response.text()
assert.equal(response.status, 200)
assert.equal(text.includes(oauthClientSecret), false)
assert.equal(text.includes("authorizationScopes"), false)
assert.equal(text.includes("activeFault"), false)
} finally {
await server.stop()
}
})
test("public scenarios, catalogs, snapshots, and events are deeply immutable runtime values", async () => {
const scenario = createDefaultScenario()
assert.equal(Object.isFrozen(scenario), true)
assert.equal(Object.isFrozen(scenario.oauth.authorizationScopes), true)
assert.throws(() => {
;(scenario as { revision: number }).revision = 999
}, TypeError)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const snapshot = server.snapshot()
assert.equal(Object.isFrozen(snapshot), true)
assert.equal(Object.isFrozen(snapshot.profile.tools), true)
assert.throws(() => {
;(snapshot.scenario as { revision: number }).revision = 777
}, TypeError)
assert.equal(server.snapshot().scenario.revision, 1)
assert.equal(Object.isFrozen(server.events()), true)
} finally {
await server.stop()
}
assert.throws(() => server.baseUrl, /has not started/)
})
test("failed live scenario activation restores the prior immutable revision transactionally", async () => {
let counter = 0
const scenario = createDefaultScenario()
const server = createEnterpriseMcpMockServer({
scenario,
secrets: { oauthClientSecret },
environment: {
now: Date.now,
randomId: () => `transaction-${++counter}`,
opaqueValue: (prefix) => `${prefix}-${++counter}`,
beforeListen: (attempt) => {
if (attempt === 2) throw new Error("injected activation failure")
},
},
})
await server.start()
const next = scenarioSchema.parse({ ...scenario, id: "servicenow-revision-two", revision: 2 })
await assert.rejects(server.updateScenario(next, 1), /injected activation failure/)
assert.equal(server.snapshot().status, "running")
assert.equal(server.snapshot().scenario.revision, 1)
assert.match(server.baseUrl, /^http:\/\/127\.0\.0\.1:\d+$/)
assert.equal((await fetch(new URL("/health", server.baseUrl))).status, 200)
await server.stop()
})
@@ -0,0 +1,285 @@
import assert from "node:assert/strict"
import { createHash, randomBytes } from "node:crypto"
import { createServer } from "node:net"
import test from "node:test"
import {
createDefaultScenario,
createEnterpriseMcpMockServer,
createFaultScenario,
getProviderProfile,
scenarioSchema,
ScenarioCredentialContinuityError,
type EnterpriseMcpScenario,
} from "../src/index.js"
import { authorizeManual, callRpc, initializeSession, rpcHeaders, sessionHeaders } from "./wire-client.js"
const oauthClientSecret = "synthetic-test-client-secret-32-bytes"
async function freePort(): Promise<number> {
const server = createServer()
await new Promise<void>((resolve, reject) => {
server.once("error", reject)
server.listen(0, "127.0.0.1", resolve)
})
const address = server.address()
if (!address || typeof address === "string") throw new Error("Expected a TCP port")
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
return address.port
}
async function createPendingAuthorization(
baseUrl: string,
scenario: EnterpriseMcpScenario,
): Promise<{ code: string; verifier: string }> {
const profile = getProviderProfile(scenario.profileId)
const redirectUri = scenario.oauth.redirectUris[0]
if (!redirectUri) throw new Error("Scenario redirect URI missing")
const verifier = randomBytes(32).toString("base64url")
const challenge = createHash("sha256").update(verifier).digest("base64url")
const authorize = new URL(profile.oauth.authorizationPath, baseUrl)
authorize.searchParams.set("response_type", "code")
authorize.searchParams.set("client_id", scenario.oauth.clientId)
authorize.searchParams.set("redirect_uri", redirectUri)
authorize.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
authorize.searchParams.set("resource", new URL(profile.endpointPath, baseUrl).href)
authorize.searchParams.set("state", "pending-across-revision")
authorize.searchParams.set("code_challenge", challenge)
authorize.searchParams.set("code_challenge_method", "S256")
const response = await fetch(authorize, { redirect: "manual" })
assert.equal(response.status, 302)
const location = response.headers.get("location")
assert.ok(location)
const code = new URL(location).searchParams.get("code")
assert.ok(code)
return { code, verifier }
}
function exchangePendingAuthorization(
baseUrl: string,
scenario: EnterpriseMcpScenario,
pending: { code: string; verifier: string },
): Promise<Response> {
const profile = getProviderProfile(scenario.profileId)
const redirectUri = scenario.oauth.redirectUris[0]
assert.ok(redirectUri)
return fetch(new URL(profile.oauth.tokenPath, baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
redirect_uri: redirectUri,
resource: new URL(profile.endpointPath, baseUrl).href,
code: pending.code,
code_verifier: pending.verifier,
}),
})
}
function refreshToken(baseUrl: string, scenario: EnterpriseMcpScenario, refreshTokenValue: string): Promise<Response> {
const profile = getProviderProfile(scenario.profileId)
return fetch(new URL(profile.oauth.tokenPath, baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
refresh_token: refreshTokenValue,
}),
})
}
test("compatible scenario activation preserves established OAuth authority but clears revision-local state", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({
scenario,
secrets: { oauthClientSecret },
port: await freePort(),
})
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const oldSession = await initializeSession(server.baseUrl, scenario, token)
const mutation = await callRpc(server.baseUrl, scenario, oldSession, 30, "tools/call", {
name: "create_incident",
arguments: {
approved: true,
idempotency_key: "continuity-operation-must-not-cross",
short_description: "Synthetic continuity boundary",
},
})
assert.equal(mutation.response.status, 200)
assert.equal(server.snapshot().counts.operations, 1)
const pending = await createPendingAuthorization(server.baseUrl, scenario)
const faulted = createFaultScenario("servicenow-inbound-quickstart", "mcp-empty-tool-catalog", 2)
const activated = await server.updateScenario(faulted, 1, {
credentialContinuity: "preserve-compatible-oauth",
})
assert.equal(activated.counts.clients, 1)
assert.equal(activated.counts.tokens, 2)
assert.equal(activated.counts.sessions, 0)
assert.equal(activated.counts.operations, 0)
assert.ok(server.events().length > 0)
assert.ok(server.events().every((event) => event.revision === 2))
const oldSessionResponse = await fetch(server.mcpUrl, {
method: "POST",
headers: sessionHeaders(
server.baseUrl,
oldSession.accessToken,
oldSession.sessionId,
oldSession.protocolVersion,
),
body: JSON.stringify({ jsonrpc: "2.0", id: 31, method: "tools/list", params: {} }),
})
assert.equal(oldSessionResponse.status, 404)
const newSession = await initializeSession(server.baseUrl, faulted, token)
const catalog = await callRpc(server.baseUrl, faulted, newSession, 32, "tools/list", {})
assert.equal(catalog.response.status, 200)
assert.deepEqual(catalog.envelope.result, { tools: [] })
assert.equal((await exchangePendingAuthorization(server.baseUrl, faulted, pending)).status, 400)
const publicEvidence = JSON.stringify({ snapshot: server.snapshot(), events: server.events() })
assert.equal(publicEvidence.includes(oauthClientSecret), false)
assert.equal(publicEvidence.includes(token.accessToken), false)
assert.equal(publicEvidence.includes(token.refreshToken), false)
assert.equal((await refreshToken(server.baseUrl, faulted, token.refreshToken)).status, 200)
} finally {
await server.stop()
}
})
test("default reset activation still invalidates all issued OAuth authority", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret }, port: await freePort() })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
assert.equal(server.snapshot().counts.tokens, 2)
const next = scenarioSchema.parse({ ...scenario, id: "servicenow-reset-revision", revision: 2 })
const activated = await server.updateScenario(next, 1)
assert.equal(activated.counts.tokens, 0)
assert.equal(activated.counts.sessions, 0)
const response = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: JSON.stringify({
jsonrpc: "2.0",
id: 40,
method: "initialize",
params: { protocolVersion: next.protocol.version, capabilities: {}, clientInfo: { name: "reset-test", version: "1" } },
}),
})
assert.equal(response.status, 401)
} finally {
await server.stop()
}
})
test("preservation rejects ephemeral ports and incompatible OAuth authority before changing the active revision", async () => {
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const revisionTwo = scenarioSchema.parse({ ...scenario, id: "servicenow-compatible-revision", revision: 2 })
const ephemeral = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await ephemeral.start()
try {
await assert.rejects(
ephemeral.updateScenario(revisionTwo, 1, { credentialContinuity: "preserve-compatible-oauth" }),
(error: unknown) => error instanceof ScenarioCredentialContinuityError && error.code === "fixed_port_required",
)
assert.equal(ephemeral.snapshot().scenario.revision, 1)
assert.equal((await fetch(new URL("/health", ephemeral.baseUrl))).status, 200)
} finally {
await ephemeral.stop()
}
const fixed = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret }, port: await freePort() })
await fixed.start()
try {
const changedClient = scenarioSchema.parse({
...scenario,
id: "servicenow-changed-client",
revision: 2,
oauth: { ...scenario.oauth, clientId: "different-pre-registered-client" },
})
const changedProvider = scenarioSchema.parse({ ...createDefaultScenario("microsoft-enterprise"), revision: 2 })
for (const incompatible of [changedClient, changedProvider]) {
await assert.rejects(
fixed.updateScenario(incompatible, 1, { credentialContinuity: "preserve-compatible-oauth" }),
(error: unknown) =>
error instanceof ScenarioCredentialContinuityError && error.code === "incompatible_oauth_authority",
)
assert.equal(fixed.snapshot().scenario.revision, 1)
}
assert.equal((await fetch(new URL("/health", fixed.baseUrl))).status, 200)
} finally {
await fixed.stop()
}
})
test("failed compatible activation rolls back the prior scenario, bearer, and MCP session", async () => {
let listenAttempt = 0
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({
scenario,
secrets: { oauthClientSecret },
port: await freePort(),
environment: {
now: Date.now,
randomId: () => `continuity-rollback-${randomBytes(8).toString("hex")}`,
opaqueValue: (prefix) => `${prefix}-${randomBytes(12).toString("base64url")}`,
beforeListen: () => {
listenAttempt += 1
if (listenAttempt === 2) throw new Error("injected compatible activation failure")
},
},
})
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const session = await initializeSession(server.baseUrl, scenario, token)
const next = scenarioSchema.parse({ ...scenario, id: "servicenow-failed-compatible-revision", revision: 2 })
await assert.rejects(
server.updateScenario(next, 1, { credentialContinuity: "preserve-compatible-oauth" }),
/injected compatible activation failure/,
)
assert.equal(server.snapshot().scenario.revision, 1)
assert.equal(server.snapshot().counts.tokens, 2)
assert.equal(server.snapshot().counts.sessions, 1)
const list = await callRpc(server.baseUrl, scenario, session, 50, "tools/list", {})
assert.equal(list.response.status, 200)
assert.ok(Array.isArray((list.envelope.result as { tools?: unknown[] } | undefined)?.tools))
} finally {
await server.stop()
}
})
test("preservation copies only OAuth records that remain unexpired at activation time", async () => {
let now = 1_700_000_000_000
let identifier = 0
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
const server = createEnterpriseMcpMockServer({
scenario,
secrets: { oauthClientSecret },
port: await freePort(),
environment: {
now: () => now,
randomId: () => `continuity-expiry-${++identifier}`,
opaqueValue: (prefix) => `${prefix}-${++identifier}`,
},
})
await server.start()
try {
await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
assert.equal(server.snapshot().counts.tokens, 2)
now += 31 * 24 * 60 * 60 * 1_000
const next = scenarioSchema.parse({ ...scenario, id: "servicenow-expired-authority", revision: 2 })
const activated = await server.updateScenario(next, 1, { credentialContinuity: "preserve-compatible-oauth" })
assert.equal(activated.counts.clients, 1)
assert.equal(activated.counts.tokens, 0)
} finally {
await server.stop()
}
})
@@ -0,0 +1,214 @@
import assert from "node:assert/strict"
import { createHash } from "node:crypto"
import test from "node:test"
import { z } from "zod"
import {
createDefaultScenario,
createEnterpriseMcpMockServer,
getProviderProfile,
probeEnterpriseMcpMockServer,
type EnterpriseMcpMockServer,
type EnterpriseMcpScenario,
} from "../src/index.js"
import { authorizeManual, initializeSession, rpcHeaders } from "./wire-client.js"
const oauthClientSecret = "slack-user-mcp-client-secret-32-bytes"
const verifier = "slack-wire-pkce-verifier-with-more-than-43-characters-1234567890"
async function authorizationCode(
server: EnterpriseMcpMockServer,
scenario: EnterpriseMcpScenario,
): Promise<string> {
const profile = getProviderProfile(scenario.profileId)
const redirectUri = scenario.oauth.redirectUris[0]
assert.ok(redirectUri)
const authorize = new URL(profile.oauth.authorizationPath, server.baseUrl)
authorize.searchParams.set("response_type", "code")
authorize.searchParams.set("client_id", scenario.oauth.clientId)
authorize.searchParams.set("redirect_uri", redirectUri)
authorize.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
authorize.searchParams.set("resource", server.mcpUrl)
authorize.searchParams.set("state", "slack-wire-state")
authorize.searchParams.set("code_challenge", createHash("sha256").update(verifier).digest("base64url"))
authorize.searchParams.set("code_challenge_method", "S256")
const response = await fetch(authorize, { redirect: "manual" })
assert.equal(response.status, 302)
const location = response.headers.get("location")
assert.ok(location)
const code = new URL(location).searchParams.get("code")
assert.ok(code)
return code
}
function tokenForm(
server: EnterpriseMcpMockServer,
scenario: EnterpriseMcpScenario,
code: string,
): URLSearchParams {
const redirectUri = scenario.oauth.redirectUris[0]
assert.ok(redirectUri)
return new URLSearchParams({
grant_type: "authorization_code",
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
redirect_uri: redirectUri,
resource: server.mcpUrl,
code,
code_verifier: verifier,
})
}
test("Slack profile returns user-token success bodies with observed expiry and token prefixes", async () => {
const scenario = createDefaultScenario("slack-user-mcp")
const profile = getProviderProfile(scenario.profileId)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const response = await fetch(new URL(profile.oauth.tokenPath, server.baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: tokenForm(server, scenario, await authorizationCode(server, scenario)),
})
assert.equal(response.status, 200)
const value: unknown = JSON.parse(await response.text())
const token = z.object({
ok: z.literal(true),
access_token: z.string(),
refresh_token: z.string(),
token_type: z.literal("user"),
expires_in: z.literal(43_200),
scope: z.string(),
}).strict().parse(value)
assert.match(token.access_token, /^xoxp-/)
assert.match(token.refresh_token, /^xoxe-1-/)
assert.equal(token.scope, scenario.oauth.authorizationScopes.join(" "))
} finally {
await server.stop()
}
})
test("Slack profile returns HTTP 200 ok:false for bad code, refresh token, and client secret", async () => {
const scenario = createDefaultScenario("slack-user-mcp")
const profile = getProviderProfile(scenario.profileId)
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const tokenUrl = new URL(profile.oauth.tokenPath, server.baseUrl)
const badCode = await fetch(tokenUrl, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: tokenForm(server, scenario, "not-a-real-code"),
})
assert.equal(badCode.status, 200)
assert.deepEqual(JSON.parse(await badCode.text()), { ok: false, error: "invalid_code" })
const badRefresh = await fetch(tokenUrl, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: scenario.oauth.clientId,
client_secret: oauthClientSecret,
refresh_token: "not-a-real-refresh-token",
}),
})
assert.equal(badRefresh.status, 200)
assert.deepEqual(JSON.parse(await badRefresh.text()), { ok: false, error: "invalid_refresh_token" })
const badClient = await fetch(tokenUrl, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: scenario.oauth.clientId,
client_secret: "wrong-slack-client-secret",
code: "not-a-real-code",
}),
})
assert.equal(badClient.status, 200)
assert.deepEqual(JSON.parse(await badClient.text()), { ok: false, error: "bad_client_secret" })
} finally {
await server.stop()
}
})
test("Slack profile strictly rejects unsupported initialize versions after authentication", async () => {
const scenario = createDefaultScenario("slack-user-mcp")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const token = await authorizeManual(server.baseUrl, scenario, oauthClientSecret)
const unsupported = await fetch(server.mcpUrl, {
method: "POST",
headers: rpcHeaders(server.baseUrl, token.accessToken),
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "slack-wire-test", version: "1" },
},
}),
})
assert.equal(unsupported.status, 400)
assert.deepEqual(JSON.parse(await unsupported.text()), {
error: "unsupported_protocol_version",
supportedVersions: ["2025-06-18"],
})
const supported = await initializeSession(server.baseUrl, scenario, token)
assert.equal(supported.protocolVersion, "2025-06-18")
} finally {
await server.stop()
}
})
test("Slack profile checks authentication before strict initialize version validation", async () => {
const scenario = createDefaultScenario("slack-user-mcp")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const response = await fetch(server.mcpUrl, {
method: "POST",
headers: {
accept: "application/json, text/event-stream",
"content-type": "application/json",
origin: new URL(server.baseUrl).origin,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "slack-wire-test", version: "1" },
},
}),
})
assert.equal(response.status, 401)
assert.equal(response.headers.has("www-authenticate"), true)
} finally {
await server.stop()
}
})
test("default probe accepts Slack user tokens only for the Slack response profile", async () => {
const scenario = createDefaultScenario("slack-user-mcp")
const server = createEnterpriseMcpMockServer({ scenario, secrets: { oauthClientSecret } })
await server.start()
try {
const result = await probeEnterpriseMcpMockServer({
baseUrl: server.baseUrl,
scenario,
credentials: { clientSecret: oauthClientSecret },
})
assert.equal(result.ok, true, result.error?.messageSafe)
assert.equal(result.negotiatedProtocolVersion, "2025-06-18")
assert.equal(result.toolCount, 3)
} finally {
await server.stop()
}
})
@@ -0,0 +1,156 @@
import { createHash, randomBytes } from "node:crypto"
import { z } from "zod"
import type { EnterpriseMcpScenario } from "../src/index.js"
import { getProviderProfile } from "../src/index.js"
const tokenSchema = z.object({ access_token: z.string(), refresh_token: z.string() })
const rpcSchema = z.object({
jsonrpc: z.literal("2.0"),
id: z.union([z.string(), z.number()]),
result: z.unknown().optional(),
error: z.object({ code: z.number(), message: z.string(), data: z.unknown().optional() }).optional(),
})
export interface WireToken {
readonly accessToken: string
readonly refreshToken: string
}
export interface WireSession extends WireToken {
readonly sessionId: string
readonly protocolVersion: string
}
async function json(response: Response): Promise<unknown> {
const parsed: unknown = JSON.parse(await response.text())
return parsed
}
export async function authorizeManual(
baseUrl: string,
scenario: EnterpriseMcpScenario,
clientSecret: string,
): Promise<WireToken> {
return authorizeClient(baseUrl, scenario, scenario.oauth.clientId, clientSecret)
}
export async function authorizeClient(
baseUrl: string,
scenario: EnterpriseMcpScenario,
clientId: string,
clientSecret?: string,
): Promise<WireToken> {
const profile = getProviderProfile(scenario.profileId)
const mcpUrl = new URL(profile.endpointPath, baseUrl).href
const verifier = randomBytes(32).toString("base64url")
const challenge = createHash("sha256").update(verifier).digest("base64url")
const redirectUri = scenario.oauth.redirectUris[0]
if (!redirectUri) throw new Error("Scenario redirect URI missing")
const authorize = new URL(profile.oauth.authorizationPath, baseUrl)
authorize.searchParams.set("response_type", "code")
authorize.searchParams.set("client_id", clientId)
authorize.searchParams.set("redirect_uri", redirectUri)
authorize.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
authorize.searchParams.set("resource", mcpUrl)
authorize.searchParams.set("state", "wire-state")
authorize.searchParams.set("code_challenge", challenge)
authorize.searchParams.set("code_challenge_method", "S256")
const authorizeResponse = await fetch(authorize, { redirect: "manual" })
if (authorizeResponse.status !== 302) throw new Error(`Authorize failed with ${authorizeResponse.status}`)
const location = authorizeResponse.headers.get("location")
if (!location) throw new Error("Authorize response omitted location")
const code = new URL(location).searchParams.get("code")
if (!code) throw new Error("Authorize response omitted code")
const form = new URLSearchParams({
grant_type: "authorization_code",
client_id: clientId,
redirect_uri: redirectUri,
code,
code_verifier: verifier,
resource: mcpUrl,
})
if (clientSecret) form.set("client_secret", clientSecret)
const tokenResponse = await fetch(new URL(profile.oauth.tokenPath, baseUrl), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: form,
})
if (tokenResponse.status !== 200) throw new Error(`Token exchange failed with ${tokenResponse.status}`)
const token = tokenSchema.parse(await json(tokenResponse))
return { accessToken: token.access_token, refreshToken: token.refresh_token }
}
export async function initializeSession(
baseUrl: string,
scenario: EnterpriseMcpScenario,
token: WireToken,
): Promise<WireSession> {
const profile = getProviderProfile(scenario.profileId)
const mcpUrl = new URL(profile.endpointPath, baseUrl)
const response = await fetch(mcpUrl, {
method: "POST",
headers: rpcHeaders(baseUrl, token.accessToken),
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: scenario.protocol.version,
capabilities: {},
clientInfo: { name: "wire-test", version: "1" },
},
}),
})
if (response.status !== 200) throw new Error(`Initialize failed with ${response.status}`)
const envelope = rpcSchema.parse(await json(response))
if (envelope.error) throw new Error(envelope.error.message)
const sessionId = response.headers.get("mcp-session-id")
const protocolVersion = response.headers.get("mcp-protocol-version")
if (!sessionId || !protocolVersion) throw new Error("Initialize response omitted session headers")
const initialized = await fetch(mcpUrl, {
method: "POST",
headers: sessionHeaders(baseUrl, token.accessToken, sessionId, protocolVersion),
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
})
if (initialized.status !== 202) throw new Error(`Initialized notification failed with ${initialized.status}`)
return { ...token, sessionId, protocolVersion }
}
export function rpcHeaders(baseUrl: string, accessToken: string): Record<string, string> {
return {
authorization: `Bearer ${accessToken}`,
accept: "application/json, text/event-stream",
"content-type": "application/json",
origin: new URL(baseUrl).origin,
}
}
export function sessionHeaders(
baseUrl: string,
accessToken: string,
sessionId: string,
protocolVersion: string,
): Record<string, string> {
return {
...rpcHeaders(baseUrl, accessToken),
"mcp-session-id": sessionId,
"mcp-protocol-version": protocolVersion,
}
}
export async function callRpc(
baseUrl: string,
scenario: EnterpriseMcpScenario,
session: WireSession,
id: number,
method: string,
params: unknown,
): Promise<{ readonly response: Response; readonly envelope: z.infer<typeof rpcSchema> }> {
const profile = getProviderProfile(scenario.profileId)
const response = await fetch(new URL(profile.endpointPath, baseUrl), {
method: "POST",
headers: sessionHeaders(baseUrl, session.accessToken, session.sessionId, session.protocolVersion),
body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
})
return { response, envelope: rpcSchema.parse(await json(response)) }
}