源码快照 @ 2026-09-02 (source-only, 剔除非源码素材)
This commit is contained in:
commit
04bac1f6e2
2200 files changed
+489415
No files matched your search
@@ -0,0 +1,132 @@
|
||||
# `@openwork/enterprise-mcp-mock-server`
|
||||
|
||||
A reusable, deterministic TypeScript package for developing and testing enterprise OAuth and remote MCP integrations without customer tenants, provider credentials, or outbound provider calls.
|
||||
|
||||
This package owns the mock **data plane**. It deliberately does not import Den, an OpenWork client, or the Enterprise Mock Lab. The lab consumes this public API and supplies the protected control plane.
|
||||
|
||||
## Design boundaries
|
||||
|
||||
- Declarative, immutable, Zod-validated scenarios.
|
||||
- One named fault at one canonical handshake phase.
|
||||
- Provider topology/catalog fixtures are separate from MCP specification behavior.
|
||||
- Literal loopback listeners only (`127.0.0.1` or `::1`).
|
||||
- Synthetic data only; no network calls leave the local mock/probe origin.
|
||||
- Tokens, codes, sessions, request bodies, client secrets, and tool arguments are not retained in trace events.
|
||||
- Bounded clients, codes, tokens, sessions, operations, counters, bodies, pages, and events.
|
||||
- Runtime lifecycle operations are serialized; reset/update drain active work before replacing state.
|
||||
- Mutations require explicit mock approval and idempotency keys. A lost response after commit remains `indeterminate` and cannot be replayed as success.
|
||||
|
||||
Mutation keys are scoped to the synthetic OAuth client/subject rather than globally across clients. `stop()` preserves the mutation ledger across a listener restart; `reset()`, scenario replacement, and instance deletion discard operations. The opt-in compatible-OAuth scenario mode still clears every operation, MCP session, authorization code, fault counter, and earlier event. Only completed `responded` entries are eligible for 24-hour expiry or bounded eviction. If 1,000 unresolved entries fill the ledger, new mutations fail closed with `MUTATION_LEDGER_CAPACITY` until the operator reconciles or resets; unresolved outcomes are never forgotten to make room.
|
||||
|
||||
## Public API
|
||||
|
||||
```ts
|
||||
import {
|
||||
createDefaultScenario,
|
||||
createEnterpriseMcpMockServer,
|
||||
createFaultScenario,
|
||||
listFaultDefinitions,
|
||||
listProviderProfiles,
|
||||
probeEnterpriseMcpMockServer,
|
||||
} from "@openwork/enterprise-mcp-mock-server"
|
||||
|
||||
const clientSecret = process.env.MOCK_OAUTH_CLIENT_SECRET ?? ""
|
||||
|
||||
const scenario = createDefaultScenario("servicenow-inbound-quickstart")
|
||||
const server = createEnterpriseMcpMockServer({
|
||||
scenario,
|
||||
secrets: { oauthClientSecret: clientSecret },
|
||||
})
|
||||
|
||||
await server.start()
|
||||
|
||||
const result = await probeEnterpriseMcpMockServer({
|
||||
baseUrl: server.baseUrl,
|
||||
scenario,
|
||||
credentials: { clientSecret },
|
||||
mode: "fixture-conformance",
|
||||
})
|
||||
|
||||
await server.stop()
|
||||
```
|
||||
|
||||
The controller exposes:
|
||||
|
||||
- `start()` / `stop()` / `reset()`
|
||||
- `updateScenario(next, expectedRevision, options?)` with optimistic revision checking
|
||||
- `snapshot()` with secret-free bounded state
|
||||
- `events()` with redacted phase-specific trace events
|
||||
- `baseUrl` and `mcpUrl` after startup
|
||||
|
||||
An optional `EnterpriseMcpMockEnvironment` injects time and ID generation for deterministic tests. Secure random defaults are used otherwise.
|
||||
|
||||
Scenario updates default to `credentialContinuity: "reset"`. A caller may explicitly request `preserve-compatible-oauth` when iterating post-authentication catalog or provider-operation faults on a fixed-port server. Preservation is rejected unless the provider fixture, endpoint/resource, OAuth registration/client, exact redirects, authorization scopes, and required resource scopes are unchanged. It copies only unexpired client registrations and their access/refresh tokens into the new state. Authorization codes, MCP sessions, operations, counters, and events are always discarded, so the client must initialize a new MCP session. OAuth-layer faults require reset mode and a new authorization flow.
|
||||
|
||||
`oauthClientSecret` is required only when a manual profile uses `client_secret_post` (for example ServiceNow or Microsoft Enterprise). It may be empty for public-client profiles and for dynamic registration, where the mock registration endpoint issues its own synthetic credential.
|
||||
|
||||
The `oauth-invalid-client` fault is profile-aware. Microsoft profiles return an Entra-shaped `invalid_client` response with safe `AADSTS7000215`, trace, correlation, and timestamp fields matching the failure class verified against a development tenant. ServiceNow returns an OAuth `invalid_client` response with ServiceNow-specific client-ID/client-secret remediation grounded in its setup and troubleshooting documentation. Neither fixture echoes the submitted secret, and the ServiceNow response wording remains explicitly synthetic until it is captured from an approved test instance. See the [Microsoft identity error reference](https://learn.microsoft.com/en-us/entra/identity-platform/reference-error-codes) and ServiceNow's [OAuth endpoint setup](https://www.servicenow.com/docs/r/platform-security/authentication/t_CreateEndpointforExternalClients.html) and [invalid-secret troubleshooting guidance](https://www.servicenow.com/docs/r/platform-security/identity/scim-troubleshooting.html).
|
||||
|
||||
## Profiles
|
||||
|
||||
| Profile | Fidelity boundary |
|
||||
| --- | --- |
|
||||
| `synthetic-enterprise-oauth-mcp` | OAuth/MCP standards-conformance profile, including DCR; no vendor claim |
|
||||
| `servicenow-inbound-quickstart` | Documented inbound Quickstart path, manual OAuth paths, `mcp_server`; synthetic provider behavior |
|
||||
| `microsoft-work-iq` | Documented Work IQ endpoint, delegated scope, ten tools, and current input names/types; bounded synthetic schemas/results plus explicit mock-only mutation controls |
|
||||
| `microsoft-enterprise` | Documented `https://mcp.svc.cloud.microsoft/enterprise`, Entra resource, `.default` token-request scope, and read-only catalog; synthetic schemas/results |
|
||||
| `agent-365-mail-v1-2026-07` | Dated preview endpoint/manifest/tool-name snapshot; synthetic tool schemas and mailbox behavior |
|
||||
|
||||
Each profile carries a stable `fixtureVersion`, documentation URLs, verification date, preview state, provider release description, and limitations. Scenarios pin that fixture version so a later profile update cannot silently reinterpret old evidence. `provenance.aspectFidelity` labels endpoint, authorization, catalog, tool-schema, provider-result, and transport fidelity independently. Provider OAuth field values may follow documented topology, but authorization behavior is labelled synthetic because the package does not reproduce Entra or ServiceNow identity systems. Provider profiles never claim that synthetic auth/results, bounded mock-only schemas, or MCP response mode/version behavior are provider-observed.
|
||||
|
||||
Work IQ follows the Microsoft tool reference updated 2026-06-03: `fetch` uses `entityUrls`; entity mutations use `parentUrl` or `entityUrl` plus a JSON-encoded `jsonBody`; actions/functions use `actionUrl`/`functionUrl`; `ask`, `list_agents`, `get_schema`, and `search_paths` use their documented input names and types. The bounded schemas are labelled synthetic because `approved` and `idempotency_key` are mock-only mutation extensions. The restricted mock schema chooses the documented `path` variant for `get_schema` and requires `path` plus `operationType`; it does not claim to encode the provider's `operationIds`/`path` exclusive-or rule.
|
||||
|
||||
The Microsoft Enterprise profile requests the documented `api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4/.default` scope. A real tenant must separately grant enabled delegated `MCP.*` permissions such as `MCP.User.Read.All`; this mock does not emulate Entra `.default` expansion. The Agent 365 Mail profile preserves dated endpoint, audience, scope, and tool-name evidence while explicitly labelling its argument shapes and results synthetic.
|
||||
|
||||
## OAuth scope model
|
||||
|
||||
`authorizationScopes` and `requiredResourceScopes` are intentionally separate. For example, `offline_access` may be requested to obtain refresh authority but is never treated as an MCP resource permission.
|
||||
|
||||
Redirect URIs must use HTTPS, except HTTP on literal numeric loopback. Credentials, fragments, custom schemes, `localhost`, and deceptive loopback-looking hostnames are rejected.
|
||||
|
||||
## Fault contract
|
||||
|
||||
`listFaultDefinitions()` returns the supported catalog. Each definition declares:
|
||||
|
||||
- a stable kebab-case identifier;
|
||||
- the exact first handshake phase;
|
||||
- canonical category and operator action;
|
||||
- retryability;
|
||||
- applicable profiles;
|
||||
- wire-level effect;
|
||||
- diagnostic level: `connection`, `readiness`, or `operation`.
|
||||
|
||||
`createFaultScenario(profileId, faultId)` adjusts any required transport detail—such as SSE response mode or catalog page size—so the selected fault is causally reachable without hidden test configuration.
|
||||
|
||||
## Probe safety
|
||||
|
||||
The included probe is intentionally restricted to literal loopback. It:
|
||||
|
||||
1. Begins with a real unauthenticated MCP request.
|
||||
2. Follows `resource_metadata` from the actual `WWW-Authenticate` challenge.
|
||||
3. Pins all discovered OAuth endpoints to the original local origin.
|
||||
4. Performs exact redirect, state, resource, scope, and PKCE binding.
|
||||
5. Negotiates MCP and verifies JSON-RPC IDs, session/protocol headers, notification status, bounded pagination, unique tools, and schemas.
|
||||
6. Preserves provider tool errors as provider outcomes.
|
||||
7. Compares observed phase/category with the scenario expectation only after independent wire classification.
|
||||
8. Cleans up sessions and revokes tokens without replacing the primary failure.
|
||||
|
||||
Probe modes are explicit:
|
||||
|
||||
- `connection-readiness` accepts any valid non-empty catalog and executes no tool;
|
||||
- `fixture-conformance` (the default) also requires the exact tool names pinned by the profile fixture and executes no tool;
|
||||
- `safe-read` adds one synthetic read-only tool call.
|
||||
|
||||
The probe bounds every response body to 1 MiB, applies a 30-second overall deadline by default, and redacts credentials and OAuth artifacts from returned error messages. An empty catalog is protocol-valid MCP; the lab classifies it as an enterprise **readiness** failure (`catalog_empty`), not as a connection failure.
|
||||
|
||||
## Validation
|
||||
|
||||
```bash
|
||||
pnpm --filter @openwork/enterprise-mcp-mock-server check
|
||||
```
|
||||
|
||||
The suite contains independent wire tests in addition to the package probe, including OAuth topology/PKCE/rotation, DCR modes, hostile Origin, cross-token session isolation, JSON-RPC/transport validation, argument schemas, mutation reconciliation, state bounds/redaction, active-request shutdown, all advertised faults, and an adversarial test proving expected fault metadata cannot manufacture a passing diagnosis.
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@openwork/enterprise-mcp-mock-server",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Deterministic enterprise OAuth and MCP mock server for development and conformance testing",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup src/index.ts --format esm --dts --clean",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "tsx --test test/*.test.ts",
|
||||
"check": "pnpm run typecheck && pnpm run test && pnpm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.30",
|
||||
"tsup": "^8.5.0",
|
||||
"tsx": "^4.23.1",
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { ProviderProfileId } from "./contracts/profile.js"
|
||||
import { createDefaultScenario, createFaultScenario, type EnterpriseMcpScenario } from "./contracts/scenario.js"
|
||||
import { getFaultDefinition, listFaultDefinitions } from "./faults/catalog.js"
|
||||
|
||||
export function createCliScenario(
|
||||
profileId: ProviderProfileId,
|
||||
activeFaultId: string | undefined,
|
||||
): EnterpriseMcpScenario {
|
||||
if (activeFaultId === undefined) return createDefaultScenario(profileId)
|
||||
|
||||
const fault = getFaultDefinition(activeFaultId)
|
||||
if (!fault || !fault.applicableProfiles.includes(profileId)) {
|
||||
const validIds = listFaultDefinitions(profileId).map((definition) => definition.id).join(", ")
|
||||
throw new Error(`Invalid ACTIVE_FAULT_ID '${activeFaultId}' for profile '${profileId}'. Valid ids: ${validIds}`)
|
||||
}
|
||||
|
||||
return createFaultScenario(profileId, fault.id)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
createEnterpriseMcpMockServer,
|
||||
providerProfileIdSchema,
|
||||
scenarioSchema,
|
||||
} from "./index.js"
|
||||
import { createCliScenario } from "./cli-scenario.js"
|
||||
|
||||
const profileId = providerProfileIdSchema.parse(process.env.PROFILE_ID)
|
||||
const port = Number(process.env.PORT ?? "3979")
|
||||
const redirectUris = (process.env.OAUTH_REDIRECT_URIS ?? "")
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean)
|
||||
const baseScenario = (() => {
|
||||
try {
|
||||
return createCliScenario(profileId, process.env.ACTIVE_FAULT_ID)
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : "Failed to configure ACTIVE_FAULT_ID")
|
||||
process.exit(1)
|
||||
}
|
||||
})()
|
||||
const scenario = redirectUris.length > 0
|
||||
? scenarioSchema.parse({
|
||||
...baseScenario,
|
||||
oauth: { ...baseScenario.oauth, redirectUris },
|
||||
})
|
||||
: baseScenario
|
||||
const server = createEnterpriseMcpMockServer({
|
||||
scenario,
|
||||
secrets: { oauthClientSecret: process.env.OAUTH_CLIENT_SECRET ?? "" },
|
||||
port,
|
||||
})
|
||||
|
||||
await server.start()
|
||||
console.log(`[enterprise-mcp-mock] ${profileId} listening at ${server.mcpUrl}`)
|
||||
|
||||
let stopping = false
|
||||
async function stop(): Promise<void> {
|
||||
if (stopping) return
|
||||
stopping = true
|
||||
await server.stop()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void stop()
|
||||
})
|
||||
process.once("SIGTERM", () => {
|
||||
void stop()
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { z } from "zod"
|
||||
import { handshakePhaseSchema, operatorActionSchema } from "./phases.js"
|
||||
import { providerProfileIdSchema } from "./profile.js"
|
||||
import { deepFreeze, type DeepReadonly } from "../immutability.js"
|
||||
|
||||
export const faultTriggerSchema = z.discriminatedUnion("occurrence", [
|
||||
z.object({ occurrence: z.literal("always") }),
|
||||
z.object({ occurrence: z.literal("once") }),
|
||||
z.object({ occurrence: z.literal("nth"), requestNumber: z.number().int().positive() }),
|
||||
])
|
||||
|
||||
export const activeFaultSchema = z.object({
|
||||
id: z.string().regex(/^[a-z][a-z0-9-]*$/),
|
||||
trigger: faultTriggerSchema,
|
||||
})
|
||||
|
||||
const rawFaultDefinitionSchema = z.object({
|
||||
id: z.string().regex(/^[a-z][a-z0-9-]*$/),
|
||||
displayName: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
phase: handshakePhaseSchema,
|
||||
category: z.string().regex(/^[a-z][a-z0-9_]*$/),
|
||||
retryable: z.boolean(),
|
||||
operatorAction: operatorActionSchema,
|
||||
applicableProfiles: z.array(providerProfileIdSchema).min(1),
|
||||
effect: z.enum([
|
||||
"omit-auth-challenge",
|
||||
"malformed-resource-metadata",
|
||||
"issuer-mismatch",
|
||||
"omit-pkce-s256",
|
||||
"reject-registration",
|
||||
"reject-client",
|
||||
"reject-grant",
|
||||
"reject-audience",
|
||||
"reject-scope",
|
||||
"reject-version",
|
||||
"malform-initialize",
|
||||
"expire-session",
|
||||
"reject-initialized",
|
||||
"wrong-content-type",
|
||||
"broken-sse",
|
||||
"empty-catalog",
|
||||
"repeat-cursor",
|
||||
"duplicate-tool",
|
||||
"invalid-tool-schema",
|
||||
"provider-authorization-denial",
|
||||
"provider-policy-denial",
|
||||
"provider-throttle",
|
||||
"provider-unavailable",
|
||||
"commit-then-disconnect",
|
||||
"redirect-uri-whitelist",
|
||||
"per-connector-redirect",
|
||||
"dcr-required",
|
||||
"method-405",
|
||||
"duplicate-amplification",
|
||||
"refresh-expired",
|
||||
"trailing-dot-url",
|
||||
"per-user-403",
|
||||
]),
|
||||
})
|
||||
|
||||
export const faultDiagnosticLevelSchema = z.enum(["connection", "readiness", "operation"])
|
||||
export type FaultDiagnosticLevel = z.infer<typeof faultDiagnosticLevelSchema>
|
||||
|
||||
type FaultDefinitionValue = z.infer<typeof rawFaultDefinitionSchema> & { readonly diagnosticLevel: FaultDiagnosticLevel }
|
||||
export type FaultDefinition = DeepReadonly<FaultDefinitionValue>
|
||||
|
||||
export const faultDefinitionSchema = rawFaultDefinitionSchema.transform((fault): FaultDefinition => deepFreeze({
|
||||
...fault,
|
||||
diagnosticLevel: fault.effect === "empty-catalog" || fault.effect === "repeat-cursor" || fault.effect === "duplicate-tool" || fault.effect === "invalid-tool-schema"
|
||||
? "readiness" as const
|
||||
: fault.phase === "PROVIDER_AUTHORIZATION" || fault.phase === "PROVIDER_EXECUTION"
|
||||
? "operation" as const
|
||||
: "connection" as const,
|
||||
}) as FaultDefinition)
|
||||
|
||||
export type FaultTrigger = z.infer<typeof faultTriggerSchema>
|
||||
export type ActiveFault = z.infer<typeof activeFaultSchema>
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export function isSafeOAuthRedirectUri(value: string): boolean {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(value)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (url.username || url.password || url.hash) return false
|
||||
if (url.protocol === "https:") return true
|
||||
if (url.protocol !== "http:") return false
|
||||
return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "::1"
|
||||
}
|
||||
|
||||
export const oauthRedirectUriSchema = z.string().superRefine((value, context) => {
|
||||
if (!isSafeOAuthRedirectUri(value)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Redirect URI must use HTTPS or HTTP on localhost, 127.0.0.1, or [::1], with no credentials or fragment",
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const handshakePhaseSchema = z.enum([
|
||||
"CONFIGURATION",
|
||||
"NETWORK_DNS",
|
||||
"NETWORK_TCP",
|
||||
"NETWORK_TLS",
|
||||
"HTTP_ROUTING",
|
||||
"AUTH_RESOURCE_DISCOVERY",
|
||||
"AUTH_ISSUER_DISCOVERY",
|
||||
"AUTH_CLIENT_REGISTRATION",
|
||||
"AUTH_USER_OR_WORKLOAD",
|
||||
"AUTH_TOKEN_ACQUISITION",
|
||||
"AUTH_RESOURCE_VALIDATION",
|
||||
"MCP_TRANSPORT",
|
||||
"MCP_VERSION",
|
||||
"MCP_INITIALIZE",
|
||||
"MCP_INITIALIZED",
|
||||
"MCP_TOOL_DISCOVERY",
|
||||
"MCP_TOOL_EXECUTION",
|
||||
"PROVIDER_AUTHORIZATION",
|
||||
"PROVIDER_EXECUTION",
|
||||
"CONTINUITY_REFRESH",
|
||||
"CONTINUITY_SESSION",
|
||||
"SHUTDOWN",
|
||||
])
|
||||
|
||||
export type HandshakePhase = z.infer<typeof handshakePhaseSchema>
|
||||
|
||||
export const operatorActionSchema = z.enum([
|
||||
"check_configuration",
|
||||
"check_network",
|
||||
"check_provider_metadata",
|
||||
"register_client",
|
||||
"reauthorize",
|
||||
"request_provider_access",
|
||||
"retry_after",
|
||||
"reinitialize",
|
||||
"inspect_provider",
|
||||
"reconcile_before_retry",
|
||||
"contact_provider",
|
||||
])
|
||||
|
||||
export type OperatorAction = z.infer<typeof operatorActionSchema>
|
||||
@@ -0,0 +1,113 @@
|
||||
import { z } from "zod"
|
||||
import { mockToolSchema } from "./tool.js"
|
||||
import { deepFreeze, type DeepReadonly } from "../immutability.js"
|
||||
|
||||
export const providerProfileIdSchema = z.enum([
|
||||
"synthetic-enterprise-oauth-mcp",
|
||||
"servicenow-inbound-quickstart",
|
||||
"microsoft-work-iq",
|
||||
"microsoft-enterprise",
|
||||
"agent-365-mail-v1-2026-07",
|
||||
"slack-user-mcp",
|
||||
])
|
||||
|
||||
export type ProviderProfileId = z.infer<typeof providerProfileIdSchema>
|
||||
|
||||
export const profileAspectFidelitySchema = z.enum([
|
||||
"provider-documented",
|
||||
"provider-observed",
|
||||
"mcp-specification",
|
||||
"spec-conformant",
|
||||
"synthetic",
|
||||
])
|
||||
|
||||
const rawProviderProfileSchema = z.object({
|
||||
id: providerProfileIdSchema,
|
||||
displayName: z.string().min(1),
|
||||
provider: z.enum(["servicenow", "microsoft", "synthetic"]),
|
||||
productSurface: z.string().min(1),
|
||||
fixtureVersion: z.string().regex(/^\d{4}-\d{2}-\d{2}\.\d+$/),
|
||||
direction: z.literal("client-to-provider"),
|
||||
endpointPath: z.string().startsWith("/"),
|
||||
canonicalEndpoint: z.url(),
|
||||
provenance: z.object({
|
||||
fidelity: z.enum(["spec-conformant", "provider-documented", "provider-observed", "synthetic"]),
|
||||
verifiedAt: z.iso.date(),
|
||||
providerRelease: z.string().min(1),
|
||||
preview: z.boolean(),
|
||||
documentationUrls: z.array(z.url()).min(1),
|
||||
limitations: z.array(z.string().min(1)).min(1),
|
||||
aspectFidelity: z.object({
|
||||
endpoint: profileAspectFidelitySchema,
|
||||
authorization: profileAspectFidelitySchema,
|
||||
catalog: profileAspectFidelitySchema,
|
||||
toolSchemas: profileAspectFidelitySchema,
|
||||
providerResults: profileAspectFidelitySchema,
|
||||
transport: profileAspectFidelitySchema,
|
||||
}),
|
||||
}),
|
||||
oauth: z.object({
|
||||
defaultRegistration: z.enum(["manual", "dynamic"]),
|
||||
registrationModes: z.array(z.enum(["manual", "dynamic"])).min(1),
|
||||
pkceRequired: z.literal(true),
|
||||
issuer: z.string().min(1),
|
||||
resource: z.string().min(1),
|
||||
audience: z.string().min(1),
|
||||
authorizationPath: z.string().startsWith("/"),
|
||||
tokenPath: z.string().startsWith("/"),
|
||||
revocationPath: z.string().startsWith("/"),
|
||||
registrationPath: z.string().startsWith("/").nullable(),
|
||||
authorizationScopes: z.array(z.string().min(1)).min(1),
|
||||
requiredResourceScopes: z.array(z.string().min(1)).min(1),
|
||||
defaultClientAuthenticationMethod: z.enum(["none", "client_secret_post"]),
|
||||
clientAuthenticationMethods: z.array(z.enum(["none", "client_secret_post"])).min(1),
|
||||
tokenResponseStyle: z.enum(["standard", "slack-user"]).default("standard"),
|
||||
}),
|
||||
protocol: z.object({
|
||||
versions: z.array(z.string().regex(/^\d{4}-\d{2}-\d{2}$/)).min(1),
|
||||
responseModes: z.array(z.enum(["json", "sse"])).min(1),
|
||||
sessionMode: z.literal("required"),
|
||||
pageSize: z.number().int().positive().max(100),
|
||||
fidelity: z.enum(["mcp-specification", "provider-observed"]),
|
||||
versionNegotiation: z.enum(["fallback", "strict"]).default("fallback"),
|
||||
}),
|
||||
tools: z.array(mockToolSchema).min(1),
|
||||
})
|
||||
|
||||
export type ProviderProfile = DeepReadonly<z.infer<typeof rawProviderProfileSchema>>
|
||||
|
||||
export const providerProfileSchema = rawProviderProfileSchema
|
||||
.superRefine((profile, context) => {
|
||||
const toolNames = new Set<string>()
|
||||
for (const [index, tool] of profile.tools.entries()) {
|
||||
if (toolNames.has(tool.name)) {
|
||||
context.addIssue({ code: "custom", message: `Duplicate tool '${tool.name}'`, path: ["tools", index, "name"] })
|
||||
}
|
||||
toolNames.add(tool.name)
|
||||
}
|
||||
if (!profile.oauth.registrationModes.includes(profile.oauth.defaultRegistration)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Default registration mode must be supported",
|
||||
path: ["oauth", "defaultRegistration"],
|
||||
})
|
||||
}
|
||||
for (const scope of profile.oauth.requiredResourceScopes) {
|
||||
if (!profile.oauth.authorizationScopes.includes(scope)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `Required resource scope '${scope}' must be requested during authorization`,
|
||||
path: ["oauth", "requiredResourceScopes"],
|
||||
})
|
||||
}
|
||||
}
|
||||
if (!profile.oauth.clientAuthenticationMethods.includes(profile.oauth.defaultClientAuthenticationMethod)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Default client authentication method must be supported",
|
||||
path: ["oauth", "defaultClientAuthenticationMethod"],
|
||||
})
|
||||
}
|
||||
})
|
||||
.transform((profile): ProviderProfile => deepFreeze(profile) as ProviderProfile)
|
||||
export type ProfileAspectFidelity = z.infer<typeof profileAspectFidelitySchema>
|
||||
@@ -0,0 +1,117 @@
|
||||
import { z } from "zod"
|
||||
import type { EnterpriseMcpScenario } from "./scenario.js"
|
||||
import type { ProviderProfile } from "./profile.js"
|
||||
import type { HandshakePhase } from "./phases.js"
|
||||
|
||||
export const enterpriseMcpMockSecretsSchema = z.object({
|
||||
oauthClientSecret: z.string().max(4_096).default(""),
|
||||
})
|
||||
|
||||
export type EnterpriseMcpMockSecrets = z.infer<typeof enterpriseMcpMockSecretsSchema>
|
||||
|
||||
export interface EnterpriseMcpMockEnvironment {
|
||||
now(): number
|
||||
randomId(): string
|
||||
opaqueValue(prefix: string): string
|
||||
beforeListen?(attempt: number): void | Promise<void>
|
||||
}
|
||||
|
||||
export type SafeTraceDetail = string | number | boolean | null | readonly string[]
|
||||
|
||||
export interface SafeTraceEvent {
|
||||
readonly id: string
|
||||
readonly occurredAt: string
|
||||
readonly correlationId: string
|
||||
readonly revision: number
|
||||
readonly phase: HandshakePhase
|
||||
readonly direction: "inbound" | "outbound" | "internal"
|
||||
readonly kind: "request" | "response" | "fault" | "lifecycle" | "security" | "mutation"
|
||||
readonly outcome: "started" | "passed" | "failed" | "applied" | "completed"
|
||||
readonly summary: string
|
||||
readonly details: Readonly<Record<string, SafeTraceDetail>>
|
||||
}
|
||||
|
||||
export interface MutationOperationSummary {
|
||||
readonly operationId: string
|
||||
readonly idempotencyKeyHash: string
|
||||
readonly tool: string
|
||||
readonly argumentsHash: string
|
||||
readonly state: "prepared" | "committed" | "responded" | "indeterminate"
|
||||
readonly resultReference: string | null
|
||||
}
|
||||
|
||||
export interface RuntimeSnapshot {
|
||||
readonly status: "idle" | "running" | "stopped"
|
||||
readonly instanceId: string
|
||||
readonly scenario: EnterpriseMcpScenario
|
||||
readonly profile: ProviderProfile
|
||||
readonly baseUrl: string | null
|
||||
readonly mcpUrl: string | null
|
||||
readonly oauth: {
|
||||
readonly authorizationServerUrl: string | null
|
||||
readonly protectedResourceMetadataUrl: string | null
|
||||
readonly registration: "manual" | "dynamic"
|
||||
readonly clientId: string
|
||||
readonly clientSecretConfigured: boolean
|
||||
}
|
||||
readonly counts: {
|
||||
readonly events: number
|
||||
readonly sessions: number
|
||||
readonly clients: number
|
||||
readonly tokens: number
|
||||
readonly operations: number
|
||||
}
|
||||
readonly operations: readonly MutationOperationSummary[]
|
||||
}
|
||||
|
||||
export interface CreateEnterpriseMcpMockServerOptions {
|
||||
readonly scenario: EnterpriseMcpScenario
|
||||
readonly secrets: EnterpriseMcpMockSecrets
|
||||
readonly host?: string
|
||||
readonly port?: number
|
||||
readonly environment?: EnterpriseMcpMockEnvironment
|
||||
}
|
||||
|
||||
export const scenarioCredentialContinuitySchema = z.enum(["reset", "preserve-compatible-oauth"])
|
||||
export type ScenarioCredentialContinuity = z.infer<typeof scenarioCredentialContinuitySchema>
|
||||
|
||||
export interface UpdateScenarioOptions {
|
||||
readonly credentialContinuity?: ScenarioCredentialContinuity
|
||||
}
|
||||
|
||||
export interface EnterpriseMcpMockServer {
|
||||
readonly baseUrl: string
|
||||
readonly mcpUrl: string
|
||||
start(): Promise<RuntimeSnapshot>
|
||||
stop(): Promise<RuntimeSnapshot>
|
||||
reset(): Promise<RuntimeSnapshot>
|
||||
updateScenario(
|
||||
next: EnterpriseMcpScenario,
|
||||
expectedRevision: number,
|
||||
options?: UpdateScenarioOptions,
|
||||
): Promise<RuntimeSnapshot>
|
||||
snapshot(): RuntimeSnapshot
|
||||
events(): readonly SafeTraceEvent[]
|
||||
}
|
||||
|
||||
export class ScenarioCredentialContinuityError extends Error {
|
||||
constructor(
|
||||
readonly code: "fixed_port_required" | "incompatible_oauth_authority" | "unsupported_mode",
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
this.name = "ScenarioCredentialContinuityError"
|
||||
}
|
||||
}
|
||||
|
||||
export class ScenarioRevisionConflictError extends Error {
|
||||
readonly expectedRevision: number
|
||||
readonly actualRevision: number
|
||||
|
||||
constructor(expectedRevision: number, actualRevision: number) {
|
||||
super(`Scenario revision conflict: expected ${expectedRevision}, current revision is ${actualRevision}`)
|
||||
this.name = "ScenarioRevisionConflictError"
|
||||
this.expectedRevision = expectedRevision
|
||||
this.actualRevision = actualRevision
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { z } from "zod"
|
||||
import { activeFaultSchema } from "./fault.js"
|
||||
import { handshakePhaseSchema } from "./phases.js"
|
||||
import { providerProfileIdSchema, type ProviderProfileId } from "./profile.js"
|
||||
import { getFaultDefinition } from "../faults/catalog.js"
|
||||
import { getProviderProfile } from "../profiles/profiles.js"
|
||||
import { oauthRedirectUriSchema } from "./oauth.js"
|
||||
import { deepFreeze, type DeepReadonly } from "../immutability.js"
|
||||
|
||||
const rawScenarioSchema = z.object({
|
||||
schemaVersion: z.literal(1),
|
||||
id: z.string().regex(/^[a-z][a-z0-9-]*$/),
|
||||
revision: z.number().int().positive(),
|
||||
profileId: providerProfileIdSchema,
|
||||
profileFixtureVersion: z.string().regex(/^\d{4}-\d{2}-\d{2}\.\d+$/),
|
||||
protocol: z.object({
|
||||
version: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
responseMode: z.enum(["json", "sse"]),
|
||||
requireSession: z.literal(true),
|
||||
pageSize: z.number().int().positive().max(100),
|
||||
}),
|
||||
oauth: z.object({
|
||||
registration: z.enum(["manual", "dynamic"]),
|
||||
clientId: z.string().min(3).max(200),
|
||||
redirectUris: z.array(oauthRedirectUriSchema).min(1).max(10),
|
||||
authorizationScopes: z.array(z.string().min(1)).min(1),
|
||||
requiredResourceScopes: z.array(z.string().min(1)).min(1),
|
||||
}),
|
||||
activeFault: activeFaultSchema.nullable(),
|
||||
expected: z.object({
|
||||
outcome: z.enum(["success", "failure"]),
|
||||
firstFailedPhase: handshakePhaseSchema.nullable(),
|
||||
category: z.string().regex(/^[a-z][a-z0-9_]*$/).nullable(),
|
||||
}),
|
||||
})
|
||||
|
||||
export type EnterpriseMcpScenario = DeepReadonly<z.infer<typeof rawScenarioSchema>>
|
||||
|
||||
export const scenarioSchema = rawScenarioSchema
|
||||
.superRefine((scenario, context) => {
|
||||
const profile = getProviderProfile(scenario.profileId)
|
||||
if (scenario.profileFixtureVersion !== profile.fixtureVersion) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `Scenario pins profile fixture '${scenario.profileFixtureVersion}', but '${profile.id}' is '${profile.fixtureVersion}'`,
|
||||
path: ["profileFixtureVersion"],
|
||||
})
|
||||
}
|
||||
if (!profile.protocol.versions.includes(scenario.protocol.version)) {
|
||||
context.addIssue({ code: "custom", message: "Protocol version is not supported by the selected profile", path: ["protocol", "version"] })
|
||||
}
|
||||
if (!profile.protocol.responseModes.includes(scenario.protocol.responseMode)) {
|
||||
context.addIssue({ code: "custom", message: "Response mode is not supported by the selected profile", path: ["protocol", "responseMode"] })
|
||||
}
|
||||
if (!profile.oauth.registrationModes.includes(scenario.oauth.registration)) {
|
||||
context.addIssue({ code: "custom", message: "OAuth registration mode is not supported by the selected profile", path: ["oauth", "registration"] })
|
||||
}
|
||||
if (scenario.oauth.authorizationScopes.some((scope) => !profile.oauth.authorizationScopes.includes(scope))) {
|
||||
context.addIssue({ code: "custom", message: "Authorization scopes must belong to the selected profile", path: ["oauth", "authorizationScopes"] })
|
||||
}
|
||||
if (profile.oauth.requiredResourceScopes.some((scope) => !scenario.oauth.authorizationScopes.includes(scope))) {
|
||||
context.addIssue({ code: "custom", message: "Authorization scopes must include every profile-required MCP resource scope", path: ["oauth", "authorizationScopes"] })
|
||||
}
|
||||
if (scenario.oauth.requiredResourceScopes.some((scope) => !scenario.oauth.authorizationScopes.includes(scope))) {
|
||||
context.addIssue({ code: "custom", message: "Resource scopes must be included in authorization scopes", path: ["oauth", "requiredResourceScopes"] })
|
||||
}
|
||||
if (
|
||||
scenario.oauth.requiredResourceScopes.length !== profile.oauth.requiredResourceScopes.length ||
|
||||
profile.oauth.requiredResourceScopes.some((scope) => !scenario.oauth.requiredResourceScopes.includes(scope))
|
||||
) {
|
||||
context.addIssue({ code: "custom", message: "Resource scopes must exactly match the pinned profile fixture", path: ["oauth", "requiredResourceScopes"] })
|
||||
}
|
||||
|
||||
if (!scenario.activeFault) {
|
||||
if (scenario.expected.outcome !== "success" || scenario.expected.firstFailedPhase !== null || scenario.expected.category !== null) {
|
||||
context.addIssue({ code: "custom", message: "A healthy scenario must expect success without a failed phase or category", path: ["expected"] })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const definition = getFaultDefinition(scenario.activeFault.id)
|
||||
if (!definition) {
|
||||
context.addIssue({ code: "custom", message: `Unknown fault '${scenario.activeFault.id}'`, path: ["activeFault", "id"] })
|
||||
return
|
||||
}
|
||||
if (!definition.applicableProfiles.includes(scenario.profileId)) {
|
||||
context.addIssue({ code: "custom", message: "Fault does not apply to the selected provider profile", path: ["activeFault", "id"] })
|
||||
}
|
||||
if (definition.effect === "broken-sse" && scenario.protocol.responseMode !== "sse") {
|
||||
context.addIssue({ code: "custom", message: "Broken SSE fault requires the SSE response mode", path: ["protocol", "responseMode"] })
|
||||
}
|
||||
if (
|
||||
scenario.expected.outcome !== "failure" ||
|
||||
scenario.expected.firstFailedPhase !== definition.phase ||
|
||||
scenario.expected.category !== definition.category
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Expected result must match the selected fault definition",
|
||||
path: ["expected"],
|
||||
})
|
||||
}
|
||||
})
|
||||
.transform((scenario): EnterpriseMcpScenario => deepFreeze(scenario) as EnterpriseMcpScenario)
|
||||
|
||||
export function createDefaultScenario(profileId: ProviderProfileId = "servicenow-inbound-quickstart"): EnterpriseMcpScenario {
|
||||
const profile = getProviderProfile(profileId)
|
||||
return scenarioSchema.parse({
|
||||
schemaVersion: 1,
|
||||
id: `${profileId}-healthy`,
|
||||
revision: 1,
|
||||
profileId,
|
||||
profileFixtureVersion: profile.fixtureVersion,
|
||||
protocol: {
|
||||
version: profile.protocol.versions[0],
|
||||
responseMode: profile.protocol.responseModes[0],
|
||||
requireSession: profile.protocol.sessionMode === "required",
|
||||
pageSize: profile.protocol.pageSize,
|
||||
},
|
||||
oauth: {
|
||||
registration: profile.oauth.defaultRegistration,
|
||||
clientId: "enterprise-mcp-test-client",
|
||||
redirectUris: ["http://127.0.0.1:19876/mcp/oauth/callback"],
|
||||
authorizationScopes: profile.oauth.authorizationScopes,
|
||||
requiredResourceScopes: profile.oauth.requiredResourceScopes,
|
||||
},
|
||||
activeFault: null,
|
||||
expected: { outcome: "success", firstFailedPhase: null, category: null },
|
||||
})
|
||||
}
|
||||
|
||||
export function createFaultScenario(
|
||||
profileId: ProviderProfileId,
|
||||
faultId: string,
|
||||
revision = 1,
|
||||
): EnterpriseMcpScenario {
|
||||
const base = createDefaultScenario(profileId)
|
||||
const fault = getFaultDefinition(faultId)
|
||||
if (!fault || !fault.applicableProfiles.includes(profileId)) {
|
||||
throw new Error(`Fault '${faultId}' does not apply to profile '${profileId}'`)
|
||||
}
|
||||
return scenarioSchema.parse({
|
||||
...base,
|
||||
id: `${profileId}-${faultId}`,
|
||||
revision,
|
||||
protocol:
|
||||
fault.effect === "broken-sse"
|
||||
? { ...base.protocol, responseMode: "sse" }
|
||||
: fault.effect === "duplicate-tool" || fault.effect === "repeat-cursor"
|
||||
? { ...base.protocol, pageSize: 1 }
|
||||
: base.protocol,
|
||||
activeFault: { id: fault.id, trigger: { occurrence: "always" } },
|
||||
expected: { outcome: "failure", firstFailedPhase: fault.phase, category: fault.category },
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export interface ToolSchemaBase {
|
||||
readonly description?: string
|
||||
}
|
||||
|
||||
export type ToolSchemaNode =
|
||||
| (ToolSchemaBase & {
|
||||
readonly type: "string"
|
||||
readonly enum?: readonly string[]
|
||||
readonly minLength?: number
|
||||
readonly maxLength?: number
|
||||
})
|
||||
| (ToolSchemaBase & {
|
||||
readonly type: "number" | "integer"
|
||||
readonly minimum?: number
|
||||
readonly maximum?: number
|
||||
})
|
||||
| (ToolSchemaBase & { readonly type: "boolean" | "null" })
|
||||
| (ToolSchemaBase & {
|
||||
readonly type: "array"
|
||||
readonly items: ToolSchemaNode
|
||||
readonly minItems?: number
|
||||
readonly maxItems?: number
|
||||
})
|
||||
| (ToolSchemaBase & {
|
||||
readonly type: "object"
|
||||
readonly properties: Readonly<Record<string, ToolSchemaNode>>
|
||||
readonly required: readonly string[]
|
||||
readonly additionalProperties: boolean | ToolSchemaNode
|
||||
})
|
||||
| (ToolSchemaBase & { readonly oneOf: readonly ToolSchemaNode[] })
|
||||
| (ToolSchemaBase & { readonly anyOf: readonly ToolSchemaNode[] })
|
||||
|
||||
export type ToolProperty = ToolSchemaNode
|
||||
export type ToolInputSchema = Extract<ToolSchemaNode, { readonly type: "object" }>
|
||||
|
||||
const maximumSchemaDepth = 10
|
||||
const maximumSchemaNodes = 512
|
||||
const maximumSchemaBytes = 64 * 1024
|
||||
const maximumProperties = 128
|
||||
const maximumCompositionBranches = 8
|
||||
const maximumDescriptionLength = 2_000
|
||||
const maximumArgumentDepth = 20
|
||||
const maximumArgumentNodes = 20_000
|
||||
const maximumArgumentIssues = 25
|
||||
|
||||
const commonKeys = new Set(["description"])
|
||||
const keysByType: Readonly<Record<string, ReadonlySet<string>>> = {
|
||||
string: new Set(["type", "description", "enum", "minLength", "maxLength"]),
|
||||
number: new Set(["type", "description", "minimum", "maximum"]),
|
||||
integer: new Set(["type", "description", "minimum", "maximum"]),
|
||||
boolean: new Set(["type", "description"]),
|
||||
null: new Set(["type", "description"]),
|
||||
array: new Set(["type", "description", "items", "minItems", "maxItems"]),
|
||||
object: new Set(["type", "description", "properties", "required", "additionalProperties"]),
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function integerInRange(value: unknown, minimum: number, maximum: number): value is number {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= minimum && value <= maximum
|
||||
}
|
||||
|
||||
function finiteNumber(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value)
|
||||
}
|
||||
|
||||
function pushUnknownKeyIssues(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string, issues: string[]): void {
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!allowed.has(key)) issues.push(`${path} uses unsupported JSON Schema keyword '${key}'`)
|
||||
}
|
||||
}
|
||||
|
||||
function schemaDefinitionIssues(value: unknown): string[] {
|
||||
const issues: string[] = []
|
||||
let remainingNodes = maximumSchemaNodes
|
||||
const ancestors = new Set<object>()
|
||||
|
||||
try {
|
||||
if (Buffer.byteLength(JSON.stringify(value), "utf8") > maximumSchemaBytes) {
|
||||
issues.push(`Tool schema exceeds ${maximumSchemaBytes} bytes`)
|
||||
return issues
|
||||
}
|
||||
} catch {
|
||||
issues.push("Tool schema must be acyclic JSON data")
|
||||
return issues
|
||||
}
|
||||
|
||||
const visit = (node: unknown, depth: number, path: string): void => {
|
||||
if (issues.length >= maximumArgumentIssues) return
|
||||
if (!isRecord(node)) {
|
||||
issues.push(`${path} must be a JSON Schema object`)
|
||||
return
|
||||
}
|
||||
if (depth > maximumSchemaDepth) {
|
||||
issues.push(`${path} exceeds maximum schema depth ${maximumSchemaDepth}`)
|
||||
return
|
||||
}
|
||||
remainingNodes -= 1
|
||||
if (remainingNodes < 0) {
|
||||
issues.push(`Tool schema exceeds ${maximumSchemaNodes} nodes`)
|
||||
return
|
||||
}
|
||||
if (ancestors.has(node)) {
|
||||
issues.push(`${path} contains a cycle`)
|
||||
return
|
||||
}
|
||||
ancestors.add(node)
|
||||
|
||||
if (node.description !== undefined && (typeof node.description !== "string" || node.description.length === 0 || node.description.length > maximumDescriptionLength)) {
|
||||
issues.push(`${path}.description must contain 1-${maximumDescriptionLength} characters`)
|
||||
}
|
||||
|
||||
const compositionKey = "oneOf" in node ? "oneOf" : "anyOf" in node ? "anyOf" : null
|
||||
if (compositionKey) {
|
||||
pushUnknownKeyIssues(node, new Set([...commonKeys, compositionKey]), path, issues)
|
||||
const branches = node[compositionKey]
|
||||
if (!Array.isArray(branches) || branches.length < 1 || branches.length > maximumCompositionBranches) {
|
||||
issues.push(`${path}.${compositionKey} must contain 1-${maximumCompositionBranches} schemas`)
|
||||
} else {
|
||||
branches.forEach((branch, index) => visit(branch, depth + 1, `${path}.${compositionKey}[${index}]`))
|
||||
}
|
||||
ancestors.delete(node)
|
||||
return
|
||||
}
|
||||
|
||||
const type = node.type
|
||||
if (typeof type !== "string" || !Object.hasOwn(keysByType, type)) {
|
||||
issues.push(`${path}.type must be one supported JSON Schema type`)
|
||||
ancestors.delete(node)
|
||||
return
|
||||
}
|
||||
pushUnknownKeyIssues(node, keysByType[type] ?? commonKeys, path, issues)
|
||||
|
||||
if (type === "string") {
|
||||
if (node.enum !== undefined && (!Array.isArray(node.enum) || node.enum.length < 1 || node.enum.length > 100 || node.enum.some((item) => typeof item !== "string"))) {
|
||||
issues.push(`${path}.enum must contain 1-100 strings`)
|
||||
}
|
||||
if (node.minLength !== undefined && !integerInRange(node.minLength, 0, 1_048_576)) issues.push(`${path}.minLength is invalid`)
|
||||
if (node.maxLength !== undefined && !integerInRange(node.maxLength, 1, 1_048_576)) issues.push(`${path}.maxLength is invalid`)
|
||||
if (finiteNumber(node.minLength) && finiteNumber(node.maxLength) && node.minLength > node.maxLength) issues.push(`${path} has minLength greater than maxLength`)
|
||||
} else if (type === "number" || type === "integer") {
|
||||
if (node.minimum !== undefined && !finiteNumber(node.minimum)) issues.push(`${path}.minimum must be finite`)
|
||||
if (node.maximum !== undefined && !finiteNumber(node.maximum)) issues.push(`${path}.maximum must be finite`)
|
||||
if (finiteNumber(node.minimum) && finiteNumber(node.maximum) && node.minimum > node.maximum) issues.push(`${path} has minimum greater than maximum`)
|
||||
} else if (type === "array") {
|
||||
if (!("items" in node)) issues.push(`${path}.items is required`)
|
||||
else visit(node.items, depth + 1, `${path}.items`)
|
||||
if (node.minItems !== undefined && !integerInRange(node.minItems, 0, 10_000)) issues.push(`${path}.minItems is invalid`)
|
||||
if (node.maxItems !== undefined && !integerInRange(node.maxItems, 1, 10_000)) issues.push(`${path}.maxItems is invalid`)
|
||||
if (finiteNumber(node.minItems) && finiteNumber(node.maxItems) && node.minItems > node.maxItems) issues.push(`${path} has minItems greater than maxItems`)
|
||||
} else if (type === "object") {
|
||||
if (!isRecord(node.properties) || Object.keys(node.properties).length > maximumProperties) {
|
||||
issues.push(`${path}.properties must be an object with at most ${maximumProperties} entries`)
|
||||
} else {
|
||||
for (const [name, property] of Object.entries(node.properties)) {
|
||||
if (!name || name.length > 128) issues.push(`${path}.properties contains an invalid property name`)
|
||||
visit(property, depth + 1, `${path}.properties.${name}`)
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(node.required) || node.required.some((name) => typeof name !== "string" || !name)) {
|
||||
issues.push(`${path}.required must be an array of property names`)
|
||||
} else {
|
||||
const unique = new Set(node.required)
|
||||
if (unique.size !== node.required.length) issues.push(`${path}.required contains duplicates`)
|
||||
for (const name of unique) {
|
||||
if (!isRecord(node.properties) || !Object.hasOwn(node.properties, name)) issues.push(`${path}.required references undeclared property '${name}'`)
|
||||
}
|
||||
}
|
||||
if (typeof node.additionalProperties !== "boolean") {
|
||||
if (!("additionalProperties" in node)) issues.push(`${path}.additionalProperties is required`)
|
||||
else visit(node.additionalProperties, depth + 1, `${path}.additionalProperties`)
|
||||
}
|
||||
}
|
||||
ancestors.delete(node)
|
||||
}
|
||||
|
||||
visit(value, 0, "$schema")
|
||||
return issues
|
||||
}
|
||||
|
||||
function schemaContract<Output extends ToolSchemaNode>(rootMustBeObject: boolean): z.ZodType<Output> {
|
||||
return z
|
||||
.unknown()
|
||||
.superRefine((value, context) => {
|
||||
for (const message of schemaDefinitionIssues(value)) context.addIssue({ code: "custom", message })
|
||||
if (rootMustBeObject && (!isRecord(value) || value.type !== "object")) {
|
||||
context.addIssue({ code: "custom", message: "A tool input schema root must have type 'object'" })
|
||||
}
|
||||
})
|
||||
.transform((value) => value as Output)
|
||||
}
|
||||
|
||||
export const toolPropertySchema = schemaContract<ToolSchemaNode>(false)
|
||||
export const toolInputSchemaSchema = schemaContract<ToolInputSchema>(true)
|
||||
|
||||
export const mockToolSchema = z.object({
|
||||
name: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),
|
||||
title: z.string().min(1).max(200),
|
||||
description: z.string().min(1).max(2_000),
|
||||
kind: z.enum(["read", "mutation"]),
|
||||
inputSchema: toolInputSchemaSchema,
|
||||
})
|
||||
|
||||
export type MockTool = z.infer<typeof mockToolSchema>
|
||||
|
||||
export type ArgumentValidationResult =
|
||||
| { readonly success: true; readonly value: Readonly<Record<string, unknown>> }
|
||||
| { readonly success: false; readonly issues: readonly string[] }
|
||||
|
||||
interface ArgumentContext {
|
||||
remainingNodes: number
|
||||
readonly issues: string[]
|
||||
}
|
||||
|
||||
function validateNode(schema: ToolSchemaNode, value: unknown, path: string, depth: number, context: ArgumentContext): void {
|
||||
if (context.issues.length >= maximumArgumentIssues) return
|
||||
context.remainingNodes -= 1
|
||||
if (context.remainingNodes < 0) {
|
||||
context.issues.push(`Arguments exceed ${maximumArgumentNodes} values`)
|
||||
return
|
||||
}
|
||||
if (depth > maximumArgumentDepth) {
|
||||
context.issues.push(`${path} exceeds maximum argument depth ${maximumArgumentDepth}`)
|
||||
return
|
||||
}
|
||||
|
||||
if ("oneOf" in schema || "anyOf" in schema) {
|
||||
const branches = "oneOf" in schema ? schema.oneOf : schema.anyOf
|
||||
const validBranches = branches.filter((branch) => {
|
||||
const branchContext: ArgumentContext = { remainingNodes: context.remainingNodes, issues: [] }
|
||||
validateNode(branch, value, path, depth + 1, branchContext)
|
||||
return branchContext.issues.length === 0
|
||||
}).length
|
||||
const valid = "oneOf" in schema ? validBranches === 1 : validBranches >= 1
|
||||
if (!valid) context.issues.push(`${path} does not match the declared schema alternatives`)
|
||||
return
|
||||
}
|
||||
|
||||
if (schema.type === "string") {
|
||||
if (typeof value !== "string") context.issues.push(`${path} must be a string`)
|
||||
else if (schema.enum && !schema.enum.includes(value)) context.issues.push(`${path} must be one of ${schema.enum.join(", ")}`)
|
||||
else if (schema.minLength !== undefined && value.length < schema.minLength) context.issues.push(`${path} is shorter than ${schema.minLength}`)
|
||||
else if (schema.maxLength !== undefined && value.length > schema.maxLength) context.issues.push(`${path} is longer than ${schema.maxLength}`)
|
||||
return
|
||||
}
|
||||
if (schema.type === "number" || schema.type === "integer") {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) context.issues.push(`${path} must be a finite number`)
|
||||
else if (schema.type === "integer" && !Number.isInteger(value)) context.issues.push(`${path} must be an integer`)
|
||||
else if (schema.minimum !== undefined && value < schema.minimum) context.issues.push(`${path} must be at least ${schema.minimum}`)
|
||||
else if (schema.maximum !== undefined && value > schema.maximum) context.issues.push(`${path} must be at most ${schema.maximum}`)
|
||||
return
|
||||
}
|
||||
if (schema.type === "boolean") {
|
||||
if (typeof value !== "boolean") context.issues.push(`${path} must be a boolean`)
|
||||
return
|
||||
}
|
||||
if (schema.type === "null") {
|
||||
if (value !== null) context.issues.push(`${path} must be null`)
|
||||
return
|
||||
}
|
||||
if (schema.type === "array") {
|
||||
if (!Array.isArray(value)) {
|
||||
context.issues.push(`${path} must be an array`)
|
||||
return
|
||||
}
|
||||
if (schema.minItems !== undefined && value.length < schema.minItems) context.issues.push(`${path} requires at least ${schema.minItems} items`)
|
||||
if (schema.maxItems !== undefined && value.length > schema.maxItems) context.issues.push(`${path} accepts at most ${schema.maxItems} items`)
|
||||
value.forEach((item, index) => validateNode(schema.items, item, `${path}[${index}]`, depth + 1, context))
|
||||
return
|
||||
}
|
||||
|
||||
if (schema.type !== "object") {
|
||||
context.issues.push(`${path} uses an unsupported schema branch`)
|
||||
return
|
||||
}
|
||||
|
||||
if (!isRecord(value)) {
|
||||
context.issues.push(`${path} must be an object`)
|
||||
return
|
||||
}
|
||||
for (const requiredName of schema.required) {
|
||||
if (!Object.hasOwn(value, requiredName)) context.issues.push(`${path} is missing required property '${requiredName}'`)
|
||||
}
|
||||
for (const [name, propertyValue] of Object.entries(value)) {
|
||||
const property = Object.hasOwn(schema.properties, name) ? schema.properties[name] : undefined
|
||||
if (property) validateNode(property, propertyValue, `${path}.${name}`, depth + 1, context)
|
||||
else if (schema.additionalProperties === false) context.issues.push(`${path} contains unknown property '${name}'`)
|
||||
else if (schema.additionalProperties !== true) validateNode(schema.additionalProperties, propertyValue, `${path}.${name}`, depth + 1, context)
|
||||
}
|
||||
}
|
||||
|
||||
export function validateToolArguments(schema: ToolInputSchema, value: unknown): ArgumentValidationResult {
|
||||
if (!isRecord(value)) return { success: false, issues: ["Arguments must be an object"] }
|
||||
const context: ArgumentContext = { remainingNodes: maximumArgumentNodes, issues: [] }
|
||||
validateNode(schema, value, "$arguments", 0, context)
|
||||
return context.issues.length === 0 ? { success: true, value } : { success: false, issues: context.issues }
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
import { faultDefinitionSchema, type FaultDefinition } from "../contracts/fault.js"
|
||||
import type { ProviderProfileId } from "../contracts/profile.js"
|
||||
import { deepFreeze } from "../immutability.js"
|
||||
|
||||
const allProfiles: ProviderProfileId[] = [
|
||||
"synthetic-enterprise-oauth-mcp",
|
||||
"servicenow-inbound-quickstart",
|
||||
"microsoft-work-iq",
|
||||
"microsoft-enterprise",
|
||||
"agent-365-mail-v1-2026-07",
|
||||
]
|
||||
|
||||
const faults = deepFreeze(faultDefinitionSchema.array().parse([
|
||||
{
|
||||
id: "oauth-missing-auth-challenge",
|
||||
displayName: "Missing OAuth challenge",
|
||||
description: "Returns HTTP 401 without a usable WWW-Authenticate resource metadata reference.",
|
||||
phase: "AUTH_RESOURCE_DISCOVERY",
|
||||
category: "oauth_discovery_resource",
|
||||
retryable: false,
|
||||
operatorAction: "check_provider_metadata",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "omit-auth-challenge",
|
||||
},
|
||||
{
|
||||
id: "oauth-malformed-resource-metadata",
|
||||
displayName: "Malformed protected-resource metadata",
|
||||
description: "Returns a protected-resource document whose resource does not match the MCP endpoint.",
|
||||
phase: "AUTH_RESOURCE_DISCOVERY",
|
||||
category: "oauth_discovery_resource",
|
||||
retryable: false,
|
||||
operatorAction: "check_provider_metadata",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "malformed-resource-metadata",
|
||||
},
|
||||
{
|
||||
id: "oauth-issuer-mismatch",
|
||||
displayName: "Authorization issuer mismatch",
|
||||
description: "Publishes authorization-server metadata with a mismatched issuer.",
|
||||
phase: "AUTH_ISSUER_DISCOVERY",
|
||||
category: "oauth_discovery_issuer",
|
||||
retryable: false,
|
||||
operatorAction: "check_provider_metadata",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "issuer-mismatch",
|
||||
},
|
||||
{
|
||||
id: "oauth-pkce-s256-unsupported",
|
||||
displayName: "PKCE S256 unavailable",
|
||||
description: "Omits S256 from authorization-server metadata.",
|
||||
phase: "AUTH_ISSUER_DISCOVERY",
|
||||
category: "oauth_pkce_unsupported",
|
||||
retryable: false,
|
||||
operatorAction: "contact_provider",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "omit-pkce-s256",
|
||||
},
|
||||
{
|
||||
id: "oauth-dynamic-registration-unsupported",
|
||||
displayName: "Dynamic registration unsupported",
|
||||
description: "Rejects RFC 7591 registration so the client must use a manual client registration.",
|
||||
phase: "AUTH_CLIENT_REGISTRATION",
|
||||
category: "oauth_client_registration",
|
||||
retryable: false,
|
||||
operatorAction: "register_client",
|
||||
applicableProfiles: ["synthetic-enterprise-oauth-mcp"],
|
||||
effect: "reject-registration",
|
||||
},
|
||||
{
|
||||
id: "oauth-invalid-client",
|
||||
displayName: "OAuth client rejected",
|
||||
description: "Token exchange returns a provider-shaped invalid_client response for a syntactically valid request: Microsoft profiles include safe AADSTS7000215 correlation evidence, while ServiceNow retains its own remediation wording.",
|
||||
phase: "AUTH_TOKEN_ACQUISITION",
|
||||
category: "oauth_client_registration",
|
||||
retryable: false,
|
||||
operatorAction: "register_client",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "reject-client",
|
||||
},
|
||||
{
|
||||
id: "oauth-invalid-grant",
|
||||
displayName: "Authorization grant rejected",
|
||||
description: "Token exchange returns invalid_grant after synthetic authorization.",
|
||||
phase: "AUTH_TOKEN_ACQUISITION",
|
||||
category: "oauth_token",
|
||||
retryable: false,
|
||||
operatorAction: "reauthorize",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "reject-grant",
|
||||
},
|
||||
{
|
||||
id: "oauth-wrong-resource-audience",
|
||||
displayName: "Wrong token resource",
|
||||
description: "Rejects the synthetic access token because its MCP resource audience is wrong.",
|
||||
phase: "AUTH_RESOURCE_VALIDATION",
|
||||
category: "oauth_wrong_audience",
|
||||
retryable: false,
|
||||
operatorAction: "reauthorize",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "reject-audience",
|
||||
},
|
||||
{
|
||||
id: "oauth-insufficient-scope",
|
||||
displayName: "MCP resource scope missing",
|
||||
description: "Returns HTTP 403 at the MCP resource before any provider operation runs.",
|
||||
phase: "AUTH_RESOURCE_VALIDATION",
|
||||
category: "oauth_insufficient_scope",
|
||||
retryable: false,
|
||||
operatorAction: "reauthorize",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "reject-scope",
|
||||
},
|
||||
{
|
||||
id: "mcp-version-unsupported",
|
||||
displayName: "MCP protocol version unsupported",
|
||||
description: "Rejects initialize because no offered version is accepted.",
|
||||
phase: "MCP_VERSION",
|
||||
category: "mcp_version",
|
||||
retryable: false,
|
||||
operatorAction: "check_configuration",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "reject-version",
|
||||
},
|
||||
{
|
||||
id: "mcp-initialize-malformed",
|
||||
displayName: "Malformed initialize response",
|
||||
description: "Returns an initialize result with a mismatched JSON-RPC identifier.",
|
||||
phase: "MCP_INITIALIZE",
|
||||
category: "mcp_initialize",
|
||||
retryable: false,
|
||||
operatorAction: "contact_provider",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "malform-initialize",
|
||||
},
|
||||
{
|
||||
id: "mcp-session-expired",
|
||||
displayName: "MCP session expired",
|
||||
description: "Expires the session on its first post-initialize request and returns HTTP 404.",
|
||||
phase: "CONTINUITY_SESSION",
|
||||
category: "mcp_session_expired",
|
||||
retryable: true,
|
||||
operatorAction: "reinitialize",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "expire-session",
|
||||
},
|
||||
{
|
||||
id: "mcp-initialized-rejected",
|
||||
displayName: "Initialized notification rejected",
|
||||
description: "Rejects notifications/initialized instead of returning HTTP 202.",
|
||||
phase: "MCP_INITIALIZED",
|
||||
category: "mcp_lifecycle",
|
||||
retryable: false,
|
||||
operatorAction: "contact_provider",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "reject-initialized",
|
||||
},
|
||||
{
|
||||
id: "mcp-wrong-content-type",
|
||||
displayName: "Wrong MCP content type",
|
||||
description: "Returns text/html for a successful-looking MCP request.",
|
||||
phase: "MCP_TRANSPORT",
|
||||
category: "mcp_transport",
|
||||
retryable: false,
|
||||
operatorAction: "check_provider_metadata",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "wrong-content-type",
|
||||
},
|
||||
{
|
||||
id: "mcp-broken-sse",
|
||||
displayName: "Malformed SSE response",
|
||||
description: "Returns an incomplete SSE data frame when the scenario uses SSE.",
|
||||
phase: "MCP_TRANSPORT",
|
||||
category: "mcp_transport",
|
||||
retryable: true,
|
||||
operatorAction: "retry_after",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "broken-sse",
|
||||
},
|
||||
{
|
||||
id: "mcp-empty-tool-catalog",
|
||||
displayName: "Empty tool catalog",
|
||||
description: "Returns a protocol-valid empty tools/list result that fails this lab's enterprise readiness policy; it is not classified as an MCP connection failure.",
|
||||
phase: "MCP_TOOL_DISCOVERY",
|
||||
category: "catalog_empty",
|
||||
retryable: false,
|
||||
operatorAction: "inspect_provider",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "empty-catalog",
|
||||
},
|
||||
{
|
||||
id: "mcp-catalog-cursor-loop",
|
||||
displayName: "Tool catalog cursor loop",
|
||||
description: "Repeats the same nextCursor so bounded clients must stop and classify the catalog as incomplete.",
|
||||
phase: "MCP_TOOL_DISCOVERY",
|
||||
category: "mcp_pagination_loop",
|
||||
retryable: false,
|
||||
operatorAction: "contact_provider",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "repeat-cursor",
|
||||
},
|
||||
{
|
||||
id: "mcp-duplicate-tool",
|
||||
displayName: "Duplicate tool across pages",
|
||||
description: "Repeats a tool name on a later catalog page.",
|
||||
phase: "MCP_TOOL_DISCOVERY",
|
||||
category: "mcp_duplicate_tool",
|
||||
retryable: false,
|
||||
operatorAction: "contact_provider",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "duplicate-tool",
|
||||
},
|
||||
{
|
||||
id: "mcp-invalid-tool-schema",
|
||||
displayName: "Invalid tool input schema",
|
||||
description: "Returns one tool whose JSON Schema required keyword has the invalid string shape instead of an array.",
|
||||
phase: "MCP_TOOL_DISCOVERY",
|
||||
category: "mcp_invalid_tool_schema",
|
||||
retryable: false,
|
||||
operatorAction: "contact_provider",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "invalid-tool-schema",
|
||||
},
|
||||
{
|
||||
id: "provider-authorization-denied",
|
||||
displayName: "Provider ACL denied",
|
||||
description: "Returns an MCP tool result with isError true and ServiceNow/Microsoft-style authorization evidence.",
|
||||
phase: "PROVIDER_AUTHORIZATION",
|
||||
category: "provider_authorization_denied",
|
||||
retryable: false,
|
||||
operatorAction: "request_provider_access",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "provider-authorization-denial",
|
||||
},
|
||||
{
|
||||
id: "provider-policy-denied",
|
||||
displayName: "Provider governance policy denied",
|
||||
description: "Returns an MCP tool result with isError true for a tenant policy or guardian decision, distinct from ACLs.",
|
||||
phase: "PROVIDER_AUTHORIZATION",
|
||||
category: "provider_policy_denied",
|
||||
retryable: false,
|
||||
operatorAction: "request_provider_access",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "provider-policy-denial",
|
||||
},
|
||||
{
|
||||
id: "provider-throttled",
|
||||
displayName: "Provider throttled",
|
||||
description: "Returns an MCP tool error carrying retry-after and a synthetic provider request identifier.",
|
||||
phase: "PROVIDER_EXECUTION",
|
||||
category: "provider_throttled",
|
||||
retryable: true,
|
||||
operatorAction: "retry_after",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "provider-throttle",
|
||||
},
|
||||
{
|
||||
id: "provider-unavailable",
|
||||
displayName: "Provider temporarily unavailable",
|
||||
description: "Returns an MCP tool error representing a transient provider 503.",
|
||||
phase: "PROVIDER_EXECUTION",
|
||||
category: "provider_unavailable",
|
||||
retryable: true,
|
||||
operatorAction: "retry_after",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "provider-unavailable",
|
||||
},
|
||||
{
|
||||
id: "mutation-timeout-after-commit",
|
||||
displayName: "Mutation committed before disconnect",
|
||||
description: "Commits the synthetic mutation ledger entry and closes the connection before returning a result.",
|
||||
phase: "PROVIDER_EXECUTION",
|
||||
category: "mutation_indeterminate",
|
||||
retryable: false,
|
||||
operatorAction: "reconcile_before_retry",
|
||||
applicableProfiles: [
|
||||
"synthetic-enterprise-oauth-mcp",
|
||||
"servicenow-inbound-quickstart",
|
||||
"microsoft-work-iq",
|
||||
"agent-365-mail-v1-2026-07",
|
||||
],
|
||||
effect: "commit-then-disconnect",
|
||||
},
|
||||
{
|
||||
id: "redirect-uri-whitelist",
|
||||
displayName: "Redirect URI whitelist rejection",
|
||||
description: "Rejects an otherwise valid OAuth authorization request because the provider has not allowlisted the exact OpenWork callback URI.",
|
||||
phase: "AUTH_USER_OR_WORKLOAD",
|
||||
category: "oauth_redirect_uri_whitelist",
|
||||
retryable: false,
|
||||
operatorAction: "register_client",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "redirect-uri-whitelist",
|
||||
},
|
||||
{
|
||||
id: "per-connector-redirect",
|
||||
displayName: "Per-connector redirect required",
|
||||
description: "Rejects the authorization-code token exchange with the same safe evidence OpenWork surfaces when a provider expects a per-connector callback instead of the shared callback.",
|
||||
phase: "AUTH_TOKEN_ACQUISITION",
|
||||
category: "oauth_token",
|
||||
retryable: false,
|
||||
operatorAction: "register_client",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "per-connector-redirect",
|
||||
},
|
||||
{
|
||||
id: "dcr-required",
|
||||
displayName: "Dynamic client registration required",
|
||||
description: "Rejects manual OAuth authorization so OpenWork can prove the gateway requires DCR before a connection can proceed.",
|
||||
phase: "AUTH_USER_OR_WORKLOAD",
|
||||
category: "oauth_dynamic_registration_required",
|
||||
retryable: false,
|
||||
operatorAction: "register_client",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "dcr-required",
|
||||
},
|
||||
{
|
||||
id: "method-405",
|
||||
displayName: "GET method returns HTTP 405",
|
||||
description: "Returns HTTP 405 to a GET request at the MCP endpoint instead of starting OAuth discovery.",
|
||||
phase: "HTTP_ROUTING",
|
||||
category: "mcp_method_405",
|
||||
retryable: false,
|
||||
operatorAction: "check_provider_metadata",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "method-405",
|
||||
},
|
||||
{
|
||||
id: "duplicate-amplification",
|
||||
displayName: "Duplicate upstream request amplification",
|
||||
description: "Models a hostile gateway that turns one MCP tool call into duplicate upstream provider requests.",
|
||||
phase: "PROVIDER_EXECUTION",
|
||||
category: "provider_duplicate_request",
|
||||
retryable: false,
|
||||
operatorAction: "reconcile_before_retry",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "duplicate-amplification",
|
||||
},
|
||||
{
|
||||
id: "refresh-expired",
|
||||
displayName: "Expired refresh credential",
|
||||
description: "Rejects refresh-token continuity with an expired-credential response that requires member reauthorization.",
|
||||
phase: "CONTINUITY_REFRESH",
|
||||
category: "oauth_credential_expired",
|
||||
retryable: true,
|
||||
operatorAction: "reauthorize",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "refresh-expired",
|
||||
},
|
||||
{
|
||||
id: "trailing-dot-url",
|
||||
displayName: "Trailing-dot OAuth URL",
|
||||
description: "Publishes an authorization-server URL whose host contains a stray trailing dot.",
|
||||
phase: "AUTH_ISSUER_DISCOVERY",
|
||||
category: "oauth_trailing_dot_url",
|
||||
retryable: false,
|
||||
operatorAction: "check_provider_metadata",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "trailing-dot-url",
|
||||
},
|
||||
{
|
||||
id: "per-user-403",
|
||||
displayName: "Per-user provider authorization 403",
|
||||
description: "Returns HTTP 403 during tool discovery with the safe authorization wording shown for user-scoped provider permission failures.",
|
||||
phase: "PROVIDER_AUTHORIZATION",
|
||||
category: "provider_per_user_403",
|
||||
retryable: false,
|
||||
operatorAction: "request_provider_access",
|
||||
applicableProfiles: allProfiles,
|
||||
effect: "per-user-403",
|
||||
},
|
||||
]))
|
||||
|
||||
export function listFaultDefinitions(profileId?: ProviderProfileId): readonly FaultDefinition[] {
|
||||
return profileId ? deepFreeze(faults.filter((fault) => fault.applicableProfiles.includes(profileId))) : faults
|
||||
}
|
||||
|
||||
export function getFaultDefinition(faultId: string): FaultDefinition | undefined {
|
||||
return faults.find((fault) => fault.id === faultId)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export type DeepReadonly<Value> =
|
||||
Value extends (...arguments_: never[]) => unknown
|
||||
? Value
|
||||
: Value extends readonly (infer Item)[]
|
||||
? readonly DeepReadonly<Item>[]
|
||||
: Value extends object
|
||||
? { readonly [Key in keyof Value]: DeepReadonly<Value[Key]> }
|
||||
: Value
|
||||
|
||||
/**
|
||||
* Recursively freezes the plain data contracts exposed by this package.
|
||||
*
|
||||
* The mock server deliberately publishes immutable scenario, profile, fault,
|
||||
* snapshot, and trace values. TypeScript's `readonly` is compile-time only;
|
||||
* freezing the runtime value prevents a JavaScript consumer from silently
|
||||
* changing active server state or shared catalog fixtures.
|
||||
*/
|
||||
export function deepFreeze<Value>(value: Value): Value {
|
||||
if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value
|
||||
|
||||
for (const nested of Object.values(value)) deepFreeze(nested)
|
||||
return Object.freeze(value)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
export {
|
||||
oauthRedirectUriSchema,
|
||||
isSafeOAuthRedirectUri,
|
||||
} from "./contracts/oauth.js"
|
||||
export {
|
||||
providerProfileIdSchema,
|
||||
providerProfileSchema,
|
||||
type ProviderProfile,
|
||||
type ProviderProfileId,
|
||||
} from "./contracts/profile.js"
|
||||
export {
|
||||
handshakePhaseSchema,
|
||||
operatorActionSchema,
|
||||
type HandshakePhase,
|
||||
type OperatorAction,
|
||||
} from "./contracts/phases.js"
|
||||
export {
|
||||
faultDefinitionSchema,
|
||||
faultDiagnosticLevelSchema,
|
||||
faultTriggerSchema,
|
||||
activeFaultSchema,
|
||||
type ActiveFault,
|
||||
type FaultDefinition,
|
||||
type FaultDiagnosticLevel,
|
||||
type FaultTrigger,
|
||||
} from "./contracts/fault.js"
|
||||
export {
|
||||
scenarioSchema,
|
||||
createDefaultScenario,
|
||||
createFaultScenario,
|
||||
type EnterpriseMcpScenario,
|
||||
} from "./contracts/scenario.js"
|
||||
export {
|
||||
mockToolSchema,
|
||||
toolInputSchemaSchema,
|
||||
toolPropertySchema,
|
||||
validateToolArguments,
|
||||
type ArgumentValidationResult,
|
||||
type MockTool,
|
||||
type ToolInputSchema,
|
||||
type ToolProperty,
|
||||
} from "./contracts/tool.js"
|
||||
export {
|
||||
enterpriseMcpMockSecretsSchema,
|
||||
scenarioCredentialContinuitySchema,
|
||||
ScenarioCredentialContinuityError,
|
||||
ScenarioRevisionConflictError,
|
||||
type CreateEnterpriseMcpMockServerOptions,
|
||||
type EnterpriseMcpMockSecrets,
|
||||
type EnterpriseMcpMockEnvironment,
|
||||
type EnterpriseMcpMockServer,
|
||||
type MutationOperationSummary,
|
||||
type RuntimeSnapshot,
|
||||
type SafeTraceDetail,
|
||||
type SafeTraceEvent,
|
||||
type ScenarioCredentialContinuity,
|
||||
type UpdateScenarioOptions,
|
||||
} from "./contracts/runtime.js"
|
||||
export type { EnterpriseMcpMockServer as EnterpriseMcpMockController } from "./contracts/runtime.js"
|
||||
export { listProviderProfiles, getProviderProfile } from "./profiles/profiles.js"
|
||||
export { listFaultDefinitions, getFaultDefinition } from "./faults/catalog.js"
|
||||
export { createEnterpriseMcpMockServer } from "./runtime/mock-server.js"
|
||||
export {
|
||||
probeEnterpriseMcpMockServer,
|
||||
type ProbeCredentials,
|
||||
type ProbeEnterpriseMcpMockServerOptions,
|
||||
type ProbeError,
|
||||
type ProbeMode,
|
||||
type ProbePhaseResult,
|
||||
type ProbeResult,
|
||||
} from "./testing/probe.js"
|
||||
@@ -0,0 +1,41 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import type { SafeTraceDetail } from "../contracts/runtime.js"
|
||||
|
||||
const secretKeyPattern = /(authorization|token|secret|password|code|verifier|session|cookie)/i
|
||||
const bearerPattern = /Bearer\s+[A-Za-z0-9._~+/=-]+/gi
|
||||
const tokenLikePattern = /\b(?:access|refresh|code|session)[-_][A-Za-z0-9._~+/=-]{8,}\b/gi
|
||||
|
||||
export function sha256(value: string): string {
|
||||
return `sha256:${createHash("sha256").update(value).digest("hex")}`
|
||||
}
|
||||
|
||||
function redactText(value: string, knownSecrets: readonly string[]): string {
|
||||
let redacted = value.replace(bearerPattern, "Bearer [REDACTED]").replace(tokenLikePattern, "[REDACTED]")
|
||||
for (const secret of knownSecrets) {
|
||||
if (secret.length > 0) redacted = redacted.split(secret).join("[REDACTED]")
|
||||
}
|
||||
return redacted.length > 500 ? `${redacted.slice(0, 497)}...` : redacted
|
||||
}
|
||||
|
||||
export function sanitizeTraceDetails(
|
||||
details: Readonly<Record<string, SafeTraceDetail>>,
|
||||
knownSecrets: readonly string[],
|
||||
): Readonly<Record<string, SafeTraceDetail>> {
|
||||
const sanitized: Record<string, SafeTraceDetail> = {}
|
||||
for (const [key, value] of Object.entries(details)) {
|
||||
if (secretKeyPattern.test(key)) {
|
||||
sanitized[key] = "[REDACTED]"
|
||||
continue
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
sanitized[key] = redactText(value, knownSecrets)
|
||||
continue
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
sanitized[key] = value.map((item) => redactText(item, knownSecrets))
|
||||
continue
|
||||
}
|
||||
sanitized[key] = value
|
||||
}
|
||||
return sanitized
|
||||
}
|
||||
@@ -0,0 +1,864 @@
|
||||
import { providerProfileSchema, type ProviderProfile, type ProviderProfileId } from "../contracts/profile.js"
|
||||
import { deepFreeze } from "../immutability.js"
|
||||
|
||||
const profiles = deepFreeze(providerProfileSchema.array().parse([
|
||||
{
|
||||
id: "synthetic-enterprise-oauth-mcp",
|
||||
fixtureVersion: "2026-07-12.1",
|
||||
displayName: "Synthetic Enterprise OAuth MCP",
|
||||
provider: "synthetic",
|
||||
productSurface: "Standards-conformance profile for OAuth DCR and MCP testing",
|
||||
direction: "client-to-provider",
|
||||
endpointPath: "/mcp",
|
||||
canonicalEndpoint: "https://mcp.example.invalid/mcp",
|
||||
provenance: {
|
||||
fidelity: "spec-conformant",
|
||||
verifiedAt: "2026-07-10",
|
||||
providerRelease: "MCP 2025-11-25 and OAuth standards-oriented synthetic profile",
|
||||
preview: false,
|
||||
documentationUrls: [
|
||||
"https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization",
|
||||
"https://modelcontextprotocol.io/specification/2025-11-25/basic/transports",
|
||||
],
|
||||
limitations: [
|
||||
"This profile intentionally represents no Microsoft or ServiceNow product.",
|
||||
"Use it for DCR and protocol conformance; use a provider profile for provider topology and catalog assertions.",
|
||||
],
|
||||
aspectFidelity: {
|
||||
endpoint: "synthetic",
|
||||
authorization: "spec-conformant",
|
||||
catalog: "synthetic",
|
||||
toolSchemas: "synthetic",
|
||||
providerResults: "synthetic",
|
||||
transport: "mcp-specification",
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
defaultRegistration: "dynamic",
|
||||
registrationModes: ["manual", "dynamic"],
|
||||
pkceRequired: true,
|
||||
issuer: "https://authorization.example.invalid",
|
||||
resource: "https://mcp.example.invalid/mcp",
|
||||
audience: "https://mcp.example.invalid/mcp",
|
||||
authorizationPath: "/oauth/authorize",
|
||||
tokenPath: "/oauth/token",
|
||||
revocationPath: "/oauth/revoke",
|
||||
registrationPath: "/oauth/register",
|
||||
authorizationScopes: ["mcp.read", "mcp.write", "offline_access"],
|
||||
requiredResourceScopes: ["mcp.read"],
|
||||
defaultClientAuthenticationMethod: "client_secret_post",
|
||||
clientAuthenticationMethods: ["none", "client_secret_post"],
|
||||
},
|
||||
protocol: {
|
||||
versions: ["2025-11-25", "2025-06-18"],
|
||||
responseModes: ["json", "sse"],
|
||||
sessionMode: "required",
|
||||
pageSize: 2,
|
||||
fidelity: "mcp-specification",
|
||||
},
|
||||
tools: [
|
||||
{
|
||||
name: "search_records",
|
||||
title: "Search records",
|
||||
description: "Returns bounded deterministic synthetic records.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { query: { type: "string", minLength: 1, maxLength: 200 } },
|
||||
required: ["query"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mutate_record",
|
||||
title: "Mutate record",
|
||||
description: "Records an approved deterministic mutation in memory.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
value: { type: "string", minLength: 1, maxLength: 200 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["value", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "servicenow-inbound-quickstart",
|
||||
fixtureVersion: "2026-07-12.1",
|
||||
displayName: "ServiceNow Inbound MCP Quickstart",
|
||||
provider: "servicenow",
|
||||
productSurface: "ServiceNow MCP Server Console — inbound Quickstart server",
|
||||
direction: "client-to-provider",
|
||||
endpointPath: "/sncapps/mcp-server/mcp/sn_mcp_server_default",
|
||||
canonicalEndpoint: "https://example.service-now.com/sncapps/mcp-server/mcp/sn_mcp_server_default",
|
||||
provenance: {
|
||||
fidelity: "provider-documented",
|
||||
verifiedAt: "2026-07-10",
|
||||
providerRelease: "Documentation snapshot; customer family and patch must be reverified",
|
||||
preview: false,
|
||||
documentationUrls: [
|
||||
"https://www.servicenow.com/docs/r/intelligent-experiences/create-mcp-server.html",
|
||||
"https://www.servicenow.com/docs/r/intelligent-experiences/connect-mcp-server-client.html",
|
||||
],
|
||||
limitations: [
|
||||
"Synthetic OAuth, roles, ACLs, domain separation, and incident data; this is not a ServiceNow instance.",
|
||||
"Patch-specific transport behavior and installed plugins must be checked against the target customer instance.",
|
||||
],
|
||||
aspectFidelity: {
|
||||
endpoint: "provider-documented",
|
||||
authorization: "synthetic",
|
||||
catalog: "synthetic",
|
||||
toolSchemas: "synthetic",
|
||||
providerResults: "synthetic",
|
||||
transport: "mcp-specification",
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
defaultRegistration: "manual",
|
||||
registrationModes: ["manual"],
|
||||
pkceRequired: true,
|
||||
issuer: "https://example.service-now.com",
|
||||
resource: "https://example.service-now.com/sncapps/mcp-server/mcp/sn_mcp_server_default",
|
||||
audience: "https://example.service-now.com/sncapps/mcp-server/mcp/sn_mcp_server_default",
|
||||
authorizationPath: "/oauth_auth.do",
|
||||
tokenPath: "/oauth_token.do",
|
||||
revocationPath: "/oauth_revoke.do",
|
||||
registrationPath: null,
|
||||
authorizationScopes: ["mcp_server"],
|
||||
requiredResourceScopes: ["mcp_server"],
|
||||
defaultClientAuthenticationMethod: "client_secret_post",
|
||||
clientAuthenticationMethods: ["client_secret_post"],
|
||||
},
|
||||
protocol: {
|
||||
versions: ["2025-11-25", "2025-06-18"],
|
||||
responseModes: ["json", "sse"],
|
||||
sessionMode: "required",
|
||||
pageSize: 2,
|
||||
fidelity: "mcp-specification",
|
||||
},
|
||||
tools: [
|
||||
{
|
||||
name: "lookup_incidents",
|
||||
title: "Look up incidents",
|
||||
description: "Returns deterministic synthetic incidents visible to the mock runtime user.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
active: { type: "boolean", description: "Only return active incidents." },
|
||||
limit: { type: "integer", minimum: 1, maximum: 20, description: "Maximum incident count." },
|
||||
},
|
||||
required: [],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get_incident",
|
||||
title: "Get incident",
|
||||
description: "Returns one synthetic incident by incident number.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { number: { type: "string", minLength: 10, maxLength: 10 } },
|
||||
required: ["number"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "summarize_incident",
|
||||
title: "Summarize incident",
|
||||
description: "Builds a deterministic summary of a synthetic incident.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { number: { type: "string", minLength: 10, maxLength: 10 } },
|
||||
required: ["number"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "create_incident",
|
||||
title: "Create incident",
|
||||
description: "Creates a synthetic incident in the in-memory mutation ledger.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
short_description: { type: "string", minLength: 3, maxLength: 160 },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
approved: { type: "boolean", description: "Explicit mock mutation approval." },
|
||||
},
|
||||
required: ["short_description", "idempotency_key", "approved"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "microsoft-work-iq",
|
||||
fixtureVersion: "2026-07-12.1",
|
||||
displayName: "Microsoft Work IQ MCP",
|
||||
provider: "microsoft",
|
||||
productSurface: "Microsoft Work IQ MCP",
|
||||
direction: "client-to-provider",
|
||||
endpointPath: "/mcp",
|
||||
canonicalEndpoint: "https://workiq.svc.cloud.microsoft/mcp",
|
||||
provenance: {
|
||||
fidelity: "provider-documented",
|
||||
verifiedAt: "2026-07-12",
|
||||
providerRelease: "Work IQ overview updated 2026-06-25; permissions updated 2026-06-17; tool reference updated 2026-06-03",
|
||||
preview: true,
|
||||
documentationUrls: [
|
||||
"https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/work-iq/mcp/overview",
|
||||
"https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/work-iq/permissions",
|
||||
"https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/work-iq/mcp/tool-reference",
|
||||
],
|
||||
limitations: [
|
||||
"Synthetic Entra authorization and synthetic Microsoft 365 content; no Copilot or Graph services are called.",
|
||||
"The ten tool names and input parameters follow the 2026-06-03 Microsoft reference; mock-only approval and idempotency fields are explicit safety extensions on mutations.",
|
||||
"The restricted mock schema supports the documented path variant of get_schema and requires path plus operationType; it does not claim the provider's operationIds/path exclusive-or constraint.",
|
||||
"Provider responses, tenant policy, entitlement, Graph behavior, and transport/version support remain synthetic or specification-driven, not provider-observed.",
|
||||
],
|
||||
aspectFidelity: {
|
||||
endpoint: "provider-documented",
|
||||
authorization: "synthetic",
|
||||
catalog: "provider-documented",
|
||||
toolSchemas: "synthetic",
|
||||
providerResults: "synthetic",
|
||||
transport: "mcp-specification",
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
defaultRegistration: "manual",
|
||||
registrationModes: ["manual"],
|
||||
pkceRequired: true,
|
||||
issuer: "https://login.microsoftonline.com/mock-tenant-id/v2.0",
|
||||
resource: "api://workiq.svc.cloud.microsoft",
|
||||
audience: "api://workiq.svc.cloud.microsoft",
|
||||
authorizationPath: "/mock-tenant-id/oauth2/v2.0/authorize",
|
||||
tokenPath: "/mock-tenant-id/oauth2/v2.0/token",
|
||||
revocationPath: "/mock-tenant-id/oauth2/v2.0/logout",
|
||||
registrationPath: null,
|
||||
authorizationScopes: ["api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask", "offline_access"],
|
||||
requiredResourceScopes: ["api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask"],
|
||||
defaultClientAuthenticationMethod: "none",
|
||||
clientAuthenticationMethods: ["none", "client_secret_post"],
|
||||
},
|
||||
protocol: {
|
||||
versions: ["2025-11-25"],
|
||||
responseModes: ["json", "sse"],
|
||||
sessionMode: "required",
|
||||
pageSize: 4,
|
||||
fidelity: "mcp-specification",
|
||||
},
|
||||
tools: [
|
||||
{
|
||||
name: "fetch",
|
||||
title: "Fetch work data",
|
||||
description: "Reads one or more Microsoft 365 entities by relative resource path; mock responses remain synthetic.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
entityUrls: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
minItems: 1,
|
||||
maxItems: 20,
|
||||
description: "Documented relative resource paths to fetch in parallel.",
|
||||
},
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Reserved by Work IQ for future use." },
|
||||
},
|
||||
required: ["entityUrls"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "create_entity",
|
||||
title: "Create entity",
|
||||
description: "Creates an entity in a documented parent collection; the mock records only a synthetic approved mutation.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
parentUrl: { type: "string", minLength: 1, maxLength: 2048, description: "Documented relative collection path." },
|
||||
jsonBody: { type: "string", minLength: 2, maxLength: 65536, description: "Documented JSON-encoded entity body string." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Reserved by Work IQ for future use." },
|
||||
approved: { type: "boolean", description: "Mock-only explicit mutation approval." },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128, description: "Mock-only replay-safety key." },
|
||||
},
|
||||
required: ["parentUrl", "jsonBody", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update_entity",
|
||||
title: "Update entity",
|
||||
description: "Updates an entity at a documented relative path; the mock records only a synthetic approved mutation.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
entityUrl: { type: "string", minLength: 1, maxLength: 2048, description: "Documented relative entity path." },
|
||||
jsonBody: { type: "string", minLength: 2, maxLength: 65536, description: "Documented JSON-encoded entity body string." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Reserved by Work IQ for future use." },
|
||||
approved: { type: "boolean", description: "Mock-only explicit mutation approval." },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128, description: "Mock-only replay-safety key." },
|
||||
},
|
||||
required: ["entityUrl", "jsonBody", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "delete_entity",
|
||||
title: "Delete entity",
|
||||
description: "Deletes an entity at a documented relative path; the mock records only a synthetic approved mutation.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
entityUrl: { type: "string", minLength: 1, maxLength: 2048, description: "Documented relative entity path." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Documented optional agent identifier." },
|
||||
approved: { type: "boolean", description: "Mock-only explicit mutation approval." },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128, description: "Mock-only replay-safety key." },
|
||||
},
|
||||
required: ["entityUrl", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "do_action",
|
||||
title: "Perform action",
|
||||
description: "Executes a documented side-effect action path; the mock records only a synthetic approved mutation.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
actionUrl: { type: "string", minLength: 1, maxLength: 2048, description: "Documented relative action path." },
|
||||
jsonBody: { type: "string", minLength: 2, maxLength: 65536, description: "Optional documented JSON-encoded action body string." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Reserved by Work IQ for future use." },
|
||||
approved: { type: "boolean", description: "Mock-only explicit mutation approval." },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128, description: "Mock-only replay-safety key." },
|
||||
},
|
||||
required: ["actionUrl", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "call_function",
|
||||
title: "Call function",
|
||||
description: "Calls a documented Microsoft Graph function path and returns deterministic synthetic data.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
functionUrl: { type: "string", minLength: 1, maxLength: 2048, description: "Documented relative function path." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Reserved by Work IQ for future use." },
|
||||
},
|
||||
required: ["functionUrl"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ask",
|
||||
title: "Ask Work IQ",
|
||||
description: "Models the documented Microsoft 365 Copilot question contract with deterministic synthetic answers.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
question: { type: "string", minLength: 1, maxLength: 4000, description: "Documented natural-language question." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Optional documented agent identifier." },
|
||||
fileUrls: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
maxItems: 20,
|
||||
description: "Optional documented OneDrive or SharePoint context URLs.",
|
||||
},
|
||||
conversationId: { type: "string", minLength: 1, maxLength: 256, description: "Optional documented conversation continuation identifier." },
|
||||
timeZone: { type: "string", minLength: 1, maxLength: 100, description: "Optional documented IANA time zone identifier." },
|
||||
},
|
||||
required: ["question"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "list_agents",
|
||||
title: "List agents",
|
||||
description: "Lists deterministic synthetic agents using the documented parameterless contract.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
required: [],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get_schema",
|
||||
title: "Get schema",
|
||||
description: "Models the documented Work IQ schema lookup contract and returns a bounded synthetic schema.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
operationIds: { type: "string", minLength: 1, maxLength: 500, description: "Documented operation ID; use this or path, not both." },
|
||||
path: { type: "string", minLength: 1, maxLength: 2048, description: "Documented API path; use this or operationIds, not both." },
|
||||
operationType: { type: "string", enum: ["fetch", "create", "update"], description: "Documented operation type." },
|
||||
format: { type: "string", enum: ["jsonschema", "typescript"], description: "Optional documented output format." },
|
||||
backend: { type: "string", minLength: 1, maxLength: 100, description: "Reserved by Work IQ for future use." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Reserved by Work IQ for future use." },
|
||||
},
|
||||
required: ["path", "operationType"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "search_paths",
|
||||
title: "Search paths",
|
||||
description: "Searches deterministic synthetic paths using the documented Work IQ filter contract.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
filter: { type: "string", minLength: 1, maxLength: 500, description: "Documented prefix or regular-expression path filter." },
|
||||
backend: { type: "string", minLength: 1, maxLength: 100, description: "Reserved by Work IQ for future use." },
|
||||
agentId: { type: "string", minLength: 1, maxLength: 200, description: "Reserved by Work IQ for future use." },
|
||||
},
|
||||
required: ["filter"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "microsoft-enterprise",
|
||||
fixtureVersion: "2026-07-12.1",
|
||||
displayName: "Microsoft MCP Server for Enterprise",
|
||||
provider: "microsoft",
|
||||
productSurface: "Microsoft MCP Server for Enterprise — read-only directory surface",
|
||||
direction: "client-to-provider",
|
||||
endpointPath: "/enterprise",
|
||||
canonicalEndpoint: "https://mcp.svc.cloud.microsoft/enterprise",
|
||||
provenance: {
|
||||
fidelity: "provider-documented",
|
||||
verifiedAt: "2026-07-12",
|
||||
providerRelease: "Microsoft MCP Registry and Microsoft Graph documentation snapshot rechecked 2026-07-12",
|
||||
preview: true,
|
||||
documentationUrls: [
|
||||
"https://github.com/mcp/io.github.microsoft/EnterpriseMCP",
|
||||
"https://learn.microsoft.com/en-us/graph/mcp-server/get-started",
|
||||
"https://learn.microsoft.com/en-us/graph/mcp-server/use-enterprise-mcp-server-copilot-studio",
|
||||
],
|
||||
limitations: [
|
||||
"Synthetic delegated Entra identity and directory data; no Microsoft Graph requests are performed.",
|
||||
"App-only identity and sovereign-cloud behavior are intentionally not claimed by this profile.",
|
||||
"The documented token-request scope is api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4/.default; the tenant grant must separately contain enabled MCP.* delegated permissions such as MCP.User.Read.All.",
|
||||
"The manual OAuth fields mirror Microsoft's connection guidance, but real Entra sign-in, consent, federation, token claims, and refresh behavior are not emulated.",
|
||||
"The local revocation route, tool input schemas, MCP transport/version behavior, and provider results are synthetic test contracts rather than Microsoft-observed wire fixtures.",
|
||||
],
|
||||
aspectFidelity: {
|
||||
endpoint: "provider-documented",
|
||||
authorization: "synthetic",
|
||||
catalog: "provider-documented",
|
||||
toolSchemas: "synthetic",
|
||||
providerResults: "synthetic",
|
||||
transport: "mcp-specification",
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
defaultRegistration: "manual",
|
||||
registrationModes: ["manual"],
|
||||
pkceRequired: true,
|
||||
issuer: "https://login.microsoftonline.com/organizations/v2.0",
|
||||
resource: "api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4",
|
||||
audience: "api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4",
|
||||
authorizationPath: "/organizations/oauth2/v2.0/authorize",
|
||||
tokenPath: "/organizations/oauth2/v2.0/token",
|
||||
revocationPath: "/organizations/oauth2/v2.0/logout",
|
||||
registrationPath: null,
|
||||
authorizationScopes: ["api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4/.default"],
|
||||
requiredResourceScopes: ["api://e8c77dc2-69b3-43f4-bc51-3213c9d915b4/.default"],
|
||||
defaultClientAuthenticationMethod: "client_secret_post",
|
||||
clientAuthenticationMethods: ["client_secret_post"],
|
||||
},
|
||||
protocol: {
|
||||
versions: ["2025-11-25"],
|
||||
responseModes: ["json", "sse"],
|
||||
sessionMode: "required",
|
||||
pageSize: 2,
|
||||
fidelity: "mcp-specification",
|
||||
},
|
||||
tools: [
|
||||
{
|
||||
name: "microsoft_graph_suggest_queries",
|
||||
title: "Suggest Graph queries",
|
||||
description: "Suggests deterministic read-only Graph query templates.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { intent: { type: "string", minLength: 1, maxLength: 300 } },
|
||||
required: ["intent"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "microsoft_graph_get",
|
||||
title: "Get Graph resource",
|
||||
description: "Returns deterministic synthetic directory data for an allowlisted path.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { path: { type: "string", minLength: 1, maxLength: 300 } },
|
||||
required: ["path"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "microsoft_graph_list_properties",
|
||||
title: "List Graph properties",
|
||||
description: "Lists deterministic properties available for a synthetic resource.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { resource: { type: "string", minLength: 1, maxLength: 120 } },
|
||||
required: ["resource"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "agent-365-mail-v1-2026-07",
|
||||
fixtureVersion: "2026-07-12.1",
|
||||
displayName: "Work IQ Mail MCP — V1 manifest snapshot (July 2026)",
|
||||
provider: "microsoft",
|
||||
productSurface: "Microsoft Work IQ Mail / Agent 365 mcp_MailTools — V1 manifest permission generation",
|
||||
direction: "client-to-provider",
|
||||
endpointPath: "/agents/tenants/mock-tenant-id/servers/mcp_MailTools",
|
||||
canonicalEndpoint: "https://agent365.svc.cloud.microsoft/agents/tenants/example-tenant-id/servers/mcp_MailTools",
|
||||
provenance: {
|
||||
fidelity: "provider-documented",
|
||||
verifiedAt: "2026-07-12",
|
||||
providerRelease: "Work IQ Mail preview reference updated 2026-06-03; tooling manifest documentation snapshot",
|
||||
preview: true,
|
||||
documentationUrls: [
|
||||
"https://learn.microsoft.com/en-us/microsoft-copilot-studio/mcp-mail-work-iq",
|
||||
"https://learn.microsoft.com/en-us/microsoft-agent-365/developer/tooling",
|
||||
],
|
||||
limitations: [
|
||||
"Microsoft marks this surface preview and explicitly warns that tool names and parameters may change.",
|
||||
"Tool names, endpoint pattern, V1 manifest scope, and audience follow the dated sources; argument schemas are bounded synthetic test contracts, not claimed vendor schema replicas.",
|
||||
"Synthetic mailbox, identity, and guardian behavior; no Agent 365 or Exchange service is contacted.",
|
||||
],
|
||||
aspectFidelity: {
|
||||
endpoint: "provider-documented",
|
||||
authorization: "synthetic",
|
||||
catalog: "provider-documented",
|
||||
toolSchemas: "synthetic",
|
||||
providerResults: "synthetic",
|
||||
transport: "mcp-specification",
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
defaultRegistration: "manual",
|
||||
registrationModes: ["manual"],
|
||||
pkceRequired: true,
|
||||
issuer: "https://login.microsoftonline.com/mock-tenant-id/v2.0",
|
||||
resource: "api://05879165-0320-489e-b644-f72b33f3edf0",
|
||||
audience: "api://05879165-0320-489e-b644-f72b33f3edf0",
|
||||
authorizationPath: "/mock-tenant-id/oauth2/v2.0/authorize",
|
||||
tokenPath: "/mock-tenant-id/oauth2/v2.0/token",
|
||||
revocationPath: "/mock-tenant-id/oauth2/v2.0/logout",
|
||||
registrationPath: null,
|
||||
authorizationScopes: ["McpServers.Mail.All", "offline_access"],
|
||||
requiredResourceScopes: ["McpServers.Mail.All"],
|
||||
defaultClientAuthenticationMethod: "none",
|
||||
clientAuthenticationMethods: ["none"],
|
||||
},
|
||||
protocol: {
|
||||
versions: ["2025-11-25"],
|
||||
responseModes: ["json", "sse"],
|
||||
sessionMode: "required",
|
||||
pageSize: 4,
|
||||
fidelity: "mcp-specification",
|
||||
},
|
||||
tools: [
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_createMessage",
|
||||
title: "Create message draft",
|
||||
description: "Creates a deterministic synthetic draft after explicit mock approval.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
subject: { type: "string", minLength: 1, maxLength: 200 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["subject", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_deleteMessage",
|
||||
title: "Delete message",
|
||||
description: "Deletes a deterministic synthetic message after explicit mock approval.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message_id: { type: "string", minLength: 1, maxLength: 120 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["message_id", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_getMessage",
|
||||
title: "Get message",
|
||||
description: "Returns one deterministic synthetic message.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { message_id: { type: "string", minLength: 1, maxLength: 120 } },
|
||||
required: ["message_id"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_listSent",
|
||||
title: "List sent messages",
|
||||
description: "Lists deterministic synthetic sent messages.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { limit: { type: "integer", minimum: 1, maximum: 20 } },
|
||||
required: [],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_reply",
|
||||
title: "Reply",
|
||||
description: "Records a synthetic reply after explicit mock approval.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message_id: { type: "string", minLength: 1, maxLength: 120 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["message_id", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_replyAll",
|
||||
title: "Reply all",
|
||||
description: "Records a synthetic reply-all after explicit mock approval.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message_id: { type: "string", minLength: 1, maxLength: 120 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["message_id", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_searchMessages",
|
||||
title: "Search messages",
|
||||
description: "Searches deterministic synthetic messages.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { query: { type: "string", minLength: 1, maxLength: 300 } },
|
||||
required: ["query"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_sendDraft",
|
||||
title: "Send draft",
|
||||
description: "Records a synthetic draft send after explicit mock approval.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message_id: { type: "string", minLength: 1, maxLength: 120 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["message_id", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_sendMail",
|
||||
title: "Send mail",
|
||||
description: "Records a synthetic mail send after explicit mock approval.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
to: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 20 },
|
||||
subject: { type: "string", minLength: 1, maxLength: 200 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["to", "subject", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mcp_MailTools_graph_mail_updateMessage",
|
||||
title: "Update message",
|
||||
description: "Updates a deterministic synthetic message after explicit mock approval.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message_id: { type: "string", minLength: 1, maxLength: 120 },
|
||||
subject: { type: "string", minLength: 1, maxLength: 200 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["message_id", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "slack-user-mcp",
|
||||
fixtureVersion: "2026-07-12.1",
|
||||
displayName: "Slack User MCP",
|
||||
provider: "synthetic",
|
||||
productSurface: "Slack remote MCP server with user-token OAuth behavior",
|
||||
direction: "client-to-provider",
|
||||
endpointPath: "/mcp",
|
||||
canonicalEndpoint: "https://mcp.slack.com/mcp",
|
||||
provenance: {
|
||||
fidelity: "provider-observed",
|
||||
verifiedAt: "2026-08-05",
|
||||
providerRelease: "Live Slack remote MCP OAuth and initialize behavior observed 2026-08-05",
|
||||
preview: false,
|
||||
documentationUrls: [
|
||||
"https://docs.slack.dev/ai/slack-mcp-server/",
|
||||
"https://api.slack.com/authentication/oauth-v2",
|
||||
],
|
||||
limitations: [
|
||||
"OAuth response and MCP version-negotiation shapes are provider-observed; identities, messages, search results, and credentials remain synthetic.",
|
||||
"The local mock serves Slack authorization and token paths from its loopback origin instead of contacting slack.com.",
|
||||
],
|
||||
aspectFidelity: {
|
||||
endpoint: "provider-documented",
|
||||
authorization: "provider-observed",
|
||||
catalog: "synthetic",
|
||||
toolSchemas: "synthetic",
|
||||
providerResults: "synthetic",
|
||||
transport: "provider-observed",
|
||||
},
|
||||
},
|
||||
oauth: {
|
||||
defaultRegistration: "manual",
|
||||
registrationModes: ["manual"],
|
||||
pkceRequired: true,
|
||||
issuer: "https://mcp.slack.com",
|
||||
resource: "https://mcp.slack.com/mcp",
|
||||
audience: "https://mcp.slack.com/mcp",
|
||||
authorizationPath: "/oauth/v2/authorize",
|
||||
tokenPath: "/api/oauth.v2.access",
|
||||
revocationPath: "/api/auth.revoke",
|
||||
registrationPath: null,
|
||||
authorizationScopes: [
|
||||
"search:read.public",
|
||||
"search:read.private",
|
||||
"chat:write",
|
||||
"channels:history",
|
||||
"groups:history",
|
||||
"im:history",
|
||||
"mpim:history",
|
||||
"users:read",
|
||||
"channels:read",
|
||||
],
|
||||
requiredResourceScopes: ["search:read.public"],
|
||||
defaultClientAuthenticationMethod: "client_secret_post",
|
||||
clientAuthenticationMethods: ["client_secret_post"],
|
||||
tokenResponseStyle: "slack-user",
|
||||
},
|
||||
protocol: {
|
||||
versions: ["2025-06-18"],
|
||||
responseModes: ["json", "sse"],
|
||||
sessionMode: "required",
|
||||
pageSize: 2,
|
||||
fidelity: "provider-observed",
|
||||
versionNegotiation: "strict",
|
||||
},
|
||||
tools: [
|
||||
{
|
||||
name: "slack_search_public",
|
||||
title: "Search public Slack messages",
|
||||
description: "Returns bounded synthetic public-channel search results.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { query: { type: "string", minLength: 1, maxLength: 200 } },
|
||||
required: ["query"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "slack_search_private",
|
||||
title: "Search private Slack messages",
|
||||
description: "Returns bounded synthetic private-channel search results.",
|
||||
kind: "read",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { query: { type: "string", minLength: 1, maxLength: 200 } },
|
||||
required: ["query"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "slack_send_message",
|
||||
title: "Send a Slack message",
|
||||
description: "Records an approved synthetic Slack message in the mock mutation ledger.",
|
||||
kind: "mutation",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
channel_id: { type: "string", minLength: 1, maxLength: 80 },
|
||||
message: { type: "string", minLength: 1, maxLength: 4000 },
|
||||
approved: { type: "boolean" },
|
||||
idempotency_key: { type: "string", minLength: 8, maxLength: 128 },
|
||||
},
|
||||
required: ["channel_id", "message", "approved", "idempotency_key"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]))
|
||||
|
||||
export function listProviderProfiles(): readonly ProviderProfile[] {
|
||||
return profiles
|
||||
}
|
||||
|
||||
export function getProviderProfile(profileId: ProviderProfileId): ProviderProfile {
|
||||
const profile = profiles.find((candidate) => candidate.id === profileId)
|
||||
if (!profile) throw new Error(`Unknown enterprise MCP profile '${profileId}'`)
|
||||
return profile
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http"
|
||||
import { z } from "zod"
|
||||
|
||||
const maximumRequestBytes = 1024 * 1024
|
||||
|
||||
export class HttpInputError extends Error {
|
||||
readonly status: number
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message)
|
||||
this.name = "HttpInputError"
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export async function readBody(request: IncomingMessage): Promise<string> {
|
||||
request.setEncoding("utf8")
|
||||
const chunks: string[] = []
|
||||
let totalBytes = 0
|
||||
for await (const chunkValue of request) {
|
||||
const chunk = typeof chunkValue === "string" ? chunkValue : String(chunkValue)
|
||||
totalBytes += Buffer.byteLength(chunk, "utf8")
|
||||
if (totalBytes > maximumRequestBytes) {
|
||||
request.resume()
|
||||
throw new HttpInputError(413, "Request body exceeds the 1 MiB test-server limit")
|
||||
}
|
||||
chunks.push(chunk)
|
||||
}
|
||||
return chunks.join("")
|
||||
}
|
||||
|
||||
export async function readJson(request: IncomingMessage): Promise<unknown> {
|
||||
if (mediaType(request.headers["content-type"]) !== "application/json") {
|
||||
throw new HttpInputError(415, "Content-Type must be application/json")
|
||||
}
|
||||
const body = await readBody(request)
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(body)
|
||||
return parsed
|
||||
} catch {
|
||||
throw new HttpInputError(400, "Request body is not valid JSON")
|
||||
}
|
||||
}
|
||||
|
||||
export async function readForm(request: IncomingMessage): Promise<URLSearchParams> {
|
||||
if (mediaType(request.headers["content-type"]) !== "application/x-www-form-urlencoded") {
|
||||
throw new HttpInputError(415, "Content-Type must be application/x-www-form-urlencoded")
|
||||
}
|
||||
return new URLSearchParams(await readBody(request))
|
||||
}
|
||||
|
||||
export function acceptedMediaTypes(header: string | readonly string[] | undefined): ReadonlySet<string> {
|
||||
const values: readonly string[] = typeof header === "string" ? [header] : header ?? []
|
||||
const accepted = new Set<string>()
|
||||
for (const entry of values.flatMap((value) => value.split(","))) {
|
||||
const [rawType, ...parameters] = entry.split(";")
|
||||
const type = rawType?.trim().toLowerCase() ?? ""
|
||||
if (!type) continue
|
||||
const qualityParameter = parameters.map((value) => value.trim()).find((value) => /^q\s*=/i.test(value))
|
||||
if (qualityParameter) {
|
||||
const quality = Number(qualityParameter.split("=", 2)[1]?.trim())
|
||||
if (!Number.isFinite(quality) || quality <= 0 || quality > 1) continue
|
||||
}
|
||||
accepted.add(type)
|
||||
}
|
||||
return accepted
|
||||
}
|
||||
|
||||
function mediaType(header: string | readonly string[] | undefined): string {
|
||||
const value = Array.isArray(header) ? header[0] : header
|
||||
return value?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
|
||||
}
|
||||
|
||||
export function sendJson(response: ServerResponse, status: number, body: unknown, headers?: Readonly<Record<string, string>>): void {
|
||||
response.writeHead(status, {
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
...headers,
|
||||
})
|
||||
response.end(JSON.stringify(body))
|
||||
}
|
||||
|
||||
export function sendSse(response: ServerResponse, body: unknown, headers?: Readonly<Record<string, string>>): void {
|
||||
response.writeHead(200, {
|
||||
"content-type": "text/event-stream; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
connection: "close",
|
||||
...headers,
|
||||
})
|
||||
response.end(`event: message\ndata: ${JSON.stringify(body)}\n\n`)
|
||||
}
|
||||
|
||||
export function sendOAuthError(response: ServerResponse, status: number, error: string, description: string): void {
|
||||
sendJson(response, status, { error, error_description: description })
|
||||
}
|
||||
|
||||
export function redirect(response: ServerResponse, location: string): void {
|
||||
response.writeHead(302, { location, "cache-control": "no-store" })
|
||||
response.end()
|
||||
}
|
||||
|
||||
export const jsonRpcRequestSchema = z.object({
|
||||
jsonrpc: z.literal("2.0"),
|
||||
id: z.union([z.string(), z.number().finite()]).optional(),
|
||||
method: z.string().min(1),
|
||||
params: z.unknown().optional(),
|
||||
})
|
||||
|
||||
export type JsonRpcRequest = z.infer<typeof jsonRpcRequestSchema>
|
||||
|
||||
export function jsonRpcResult(id: string | number, result: unknown): unknown {
|
||||
return { jsonrpc: "2.0", id, result }
|
||||
}
|
||||
|
||||
export function jsonRpcError(id: string | number | null, code: number, message: string, data?: unknown): unknown {
|
||||
return { jsonrpc: "2.0", id, error: { code, message, ...(data === undefined ? {} : { data }) } }
|
||||
}
|
||||
|
||||
export function requestUrl(request: IncomingMessage, baseUrl: string): URL {
|
||||
return new URL(request.url ?? "/", baseUrl)
|
||||
}
|
||||
@@ -0,0 +1,808 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http"
|
||||
import { z } from "zod"
|
||||
import type { EnterpriseMcpScenario } from "../contracts/scenario.js"
|
||||
import type { ProviderProfile } from "../contracts/profile.js"
|
||||
import type { FaultDefinition } from "../contracts/fault.js"
|
||||
import { validateToolArguments, type MockTool } from "../contracts/tool.js"
|
||||
import type { AccessTokenRecord, InstanceState, SessionRecord } from "../runtime/instance-state.js"
|
||||
import {
|
||||
jsonRpcError,
|
||||
jsonRpcRequestSchema,
|
||||
jsonRpcResult,
|
||||
acceptedMediaTypes,
|
||||
HttpInputError,
|
||||
readJson,
|
||||
sendJson,
|
||||
sendSse,
|
||||
type JsonRpcRequest,
|
||||
} from "./http-utils.js"
|
||||
|
||||
interface McpRequestContext {
|
||||
readonly request: IncomingMessage
|
||||
readonly response: ServerResponse
|
||||
readonly baseUrl: string
|
||||
readonly correlationId: string
|
||||
readonly scenario: EnterpriseMcpScenario
|
||||
readonly profile: ProviderProfile
|
||||
readonly state: InstanceState
|
||||
readonly activeFault: FaultDefinition | undefined
|
||||
}
|
||||
|
||||
const initializeParamsSchema = z.object({
|
||||
protocolVersion: z.string().min(1),
|
||||
capabilities: z.record(z.string(), z.unknown()),
|
||||
clientInfo: z.object({ name: z.string().min(1), version: z.string().min(1) }),
|
||||
})
|
||||
|
||||
const listToolsParamsSchema = z.object({ cursor: z.string().optional() }).optional()
|
||||
const callToolParamsSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
arguments: z.unknown().optional(),
|
||||
})
|
||||
const sessionLifetimeMs = 24 * 60 * 60 * 1000
|
||||
|
||||
function faultApplies(context: McpRequestContext, effect: FaultDefinition["effect"]): boolean {
|
||||
return context.activeFault?.effect === effect && context.state.shouldApplyFault(context.activeFault, context.scenario)
|
||||
}
|
||||
|
||||
function emitFault(context: McpRequestContext, summary: string): void {
|
||||
const fault = context.activeFault
|
||||
if (!fault) return
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: fault.phase,
|
||||
direction: "outbound",
|
||||
kind: "fault",
|
||||
outcome: "applied",
|
||||
summary,
|
||||
details: { faultId: fault.id, category: fault.category },
|
||||
})
|
||||
}
|
||||
|
||||
function sendRpc(context: McpRequestContext, body: unknown, headers?: Readonly<Record<string, string>>): boolean {
|
||||
if (faultApplies(context, "wrong-content-type")) {
|
||||
emitFault(context, "Returned HTML instead of an MCP response")
|
||||
context.response.writeHead(200, {
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
...headers,
|
||||
})
|
||||
context.response.end("<!doctype html><title>Synthetic login interception</title>")
|
||||
return false
|
||||
}
|
||||
if (context.scenario.protocol.responseMode === "sse") {
|
||||
if (faultApplies(context, "broken-sse")) {
|
||||
emitFault(context, "Returned an incomplete SSE data frame")
|
||||
context.response.writeHead(200, {
|
||||
"content-type": "text/event-stream; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
...headers,
|
||||
})
|
||||
context.response.end("event: message\ndata: {\"jsonrpc\":")
|
||||
return false
|
||||
}
|
||||
sendSse(context.response, body, headers)
|
||||
return true
|
||||
}
|
||||
sendJson(context.response, 200, body, headers)
|
||||
return true
|
||||
}
|
||||
|
||||
function extractBearer(request: IncomingMessage): string | undefined {
|
||||
const authorization = request.headers.authorization
|
||||
const match = /^Bearer +([^\s]+)$/i.exec(authorization ?? "")
|
||||
return match?.[1]
|
||||
}
|
||||
|
||||
function unauthorizedChallenge(context: McpRequestContext): void {
|
||||
if (faultApplies(context, "omit-auth-challenge")) {
|
||||
emitFault(context, "Returned 401 without OAuth protected-resource metadata")
|
||||
sendJson(context.response, 401, { error: "unauthorized" })
|
||||
return
|
||||
}
|
||||
const resourceMetadata = new URL(`/.well-known/oauth-protected-resource${context.profile.endpointPath}`, context.baseUrl).href
|
||||
sendJson(
|
||||
context.response,
|
||||
401,
|
||||
{ error: "unauthorized" },
|
||||
{ "www-authenticate": `Bearer resource_metadata="${resourceMetadata}", scope="${context.scenario.oauth.requiredResourceScopes.join(" ")}"` },
|
||||
)
|
||||
}
|
||||
|
||||
function validateOrigin(context: McpRequestContext): boolean {
|
||||
const origin = context.request.headers.origin
|
||||
if (origin && origin !== new URL(context.baseUrl).origin) {
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: "MCP_TRANSPORT",
|
||||
direction: "inbound",
|
||||
kind: "security",
|
||||
outcome: "failed",
|
||||
summary: "Rejected an untrusted Origin header",
|
||||
details: { origin },
|
||||
})
|
||||
sendJson(context.response, 403, { error: "origin_not_allowed" })
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function validateAccept(context: McpRequestContext): boolean {
|
||||
const accepted = acceptedMediaTypes(context.request.headers.accept)
|
||||
if (accepted.has("application/json") && accepted.has("text/event-stream")) return true
|
||||
sendJson(context.response, 406, {
|
||||
error: "not_acceptable",
|
||||
message: "Accept must include application/json and text/event-stream",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
function resolveSession(context: McpRequestContext, token: AccessTokenRecord): SessionRecord | undefined {
|
||||
const sessionHeader = context.request.headers["mcp-session-id"]
|
||||
const sessionId = Array.isArray(sessionHeader) ? sessionHeader[0] : sessionHeader
|
||||
if (!sessionId) {
|
||||
sendJson(context.response, 400, { error: "missing_mcp_session" })
|
||||
return undefined
|
||||
}
|
||||
const session = context.state.sessions.get(sessionId)
|
||||
if (!session) {
|
||||
sendJson(context.response, 404, { error: "mcp_session_not_found" })
|
||||
return undefined
|
||||
}
|
||||
if (
|
||||
session.tokenFamilyId !== token.familyId ||
|
||||
session.profileId !== context.profile.id ||
|
||||
session.scenarioRevision !== context.scenario.revision
|
||||
) {
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: "CONTINUITY_SESSION",
|
||||
direction: "inbound",
|
||||
kind: "security",
|
||||
outcome: "failed",
|
||||
summary: "Rejected an MCP session outside its token, profile, or scenario boundary",
|
||||
})
|
||||
sendJson(context.response, 403, { error: "mcp_session_binding_mismatch" })
|
||||
return undefined
|
||||
}
|
||||
if (faultApplies(context, "expire-session")) {
|
||||
context.state.sessions.delete(sessionId)
|
||||
emitFault(context, "Expired the MCP session before the post-initialize request")
|
||||
sendJson(context.response, 404, { error: "mcp_session_expired" })
|
||||
return undefined
|
||||
}
|
||||
const protocolHeader = context.request.headers["mcp-protocol-version"]
|
||||
const protocolVersion = Array.isArray(protocolHeader) ? protocolHeader[0] : protocolHeader
|
||||
if (protocolVersion !== session.protocolVersion) {
|
||||
sendJson(context.response, 400, { error: "mcp_protocol_version_mismatch" })
|
||||
return undefined
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
export async function handleMcpRequest(context: McpRequestContext): Promise<boolean> {
|
||||
const { request, response, scenario, profile, state, correlationId, baseUrl } = context
|
||||
const mcpUrl = new URL(profile.endpointPath, baseUrl).href
|
||||
const bearer = extractBearer(request)
|
||||
|
||||
if (!validateOrigin(context)) return true
|
||||
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "MCP_TRANSPORT",
|
||||
direction: "inbound",
|
||||
kind: "request",
|
||||
outcome: "started",
|
||||
summary: "MCP endpoint request received",
|
||||
details: { method: request.method ?? "UNKNOWN", path: profile.endpointPath },
|
||||
})
|
||||
|
||||
if (request.method === "GET" && faultApplies(context, "method-405")) {
|
||||
emitFault(context, "Returned HTTP 405 to a GET request at the MCP endpoint")
|
||||
sendJson(response, 405, { error: "method_not_allowed", message: "HTTP 405 on GET" }, { allow: "POST, DELETE" })
|
||||
return true
|
||||
}
|
||||
|
||||
if (!bearer) {
|
||||
unauthorizedChallenge(context)
|
||||
return true
|
||||
}
|
||||
|
||||
const token = state.tokens.get(bearer)
|
||||
if (faultApplies(context, "reject-audience") || !token || token.expiresAt < state.now() || token.resource !== mcpUrl) {
|
||||
if (context.activeFault?.effect === "reject-audience") emitFault(context, "Rejected the access token MCP resource audience")
|
||||
unauthorizedChallenge(context)
|
||||
return true
|
||||
}
|
||||
if (
|
||||
faultApplies(context, "reject-scope") ||
|
||||
scenario.oauth.requiredResourceScopes.some((scope) => !token.scopes.includes(scope))
|
||||
) {
|
||||
if (context.activeFault?.effect === "reject-scope") emitFault(context, "Rejected the access token for insufficient MCP resource scope")
|
||||
sendJson(response, 403, { error: "insufficient_scope" }, { "www-authenticate": `Bearer error="insufficient_scope"` })
|
||||
return true
|
||||
}
|
||||
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_RESOURCE_VALIDATION",
|
||||
direction: "internal",
|
||||
kind: "lifecycle",
|
||||
outcome: "passed",
|
||||
summary: "Accepted synthetic access token for this MCP resource",
|
||||
details: { scopeCount: token.scopes.length, subjectHash: "synthetic-subject" },
|
||||
})
|
||||
|
||||
if (request.method === "DELETE") {
|
||||
const sessionHeader = request.headers["mcp-session-id"]
|
||||
const sessionId = Array.isArray(sessionHeader) ? sessionHeader[0] : sessionHeader
|
||||
if (!sessionId) {
|
||||
sendJson(response, 404, { error: "mcp_session_not_found" })
|
||||
return true
|
||||
}
|
||||
const session = state.sessions.get(sessionId)
|
||||
if (!session) {
|
||||
sendJson(response, 404, { error: "mcp_session_not_found" })
|
||||
return true
|
||||
}
|
||||
if (
|
||||
session.tokenFamilyId !== token.familyId ||
|
||||
session.profileId !== profile.id ||
|
||||
session.scenarioRevision !== scenario.revision
|
||||
) {
|
||||
sendJson(response, 403, { error: "mcp_session_binding_mismatch" })
|
||||
return true
|
||||
}
|
||||
const protocolHeader = request.headers["mcp-protocol-version"]
|
||||
const protocolVersion = Array.isArray(protocolHeader) ? protocolHeader[0] : protocolHeader
|
||||
if (protocolVersion !== session.protocolVersion) {
|
||||
sendJson(response, 400, { error: "mcp_protocol_version_mismatch" })
|
||||
return true
|
||||
}
|
||||
state.sessions.delete(sessionId)
|
||||
response.writeHead(204, { "cache-control": "no-store" })
|
||||
response.end()
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "SHUTDOWN",
|
||||
direction: "internal",
|
||||
kind: "lifecycle",
|
||||
outcome: "completed",
|
||||
summary: "Terminated the synthetic MCP session",
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
if (request.method !== "POST") {
|
||||
response.writeHead(405, { allow: "POST, DELETE", "cache-control": "no-store" })
|
||||
response.end()
|
||||
return true
|
||||
}
|
||||
if (!validateAccept(context)) return true
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await readJson(request)
|
||||
} catch (error) {
|
||||
if (error instanceof HttpInputError && error.status === 400) {
|
||||
sendRpc(context, jsonRpcError(null, -32700, "Parse error"))
|
||||
return true
|
||||
}
|
||||
throw error
|
||||
}
|
||||
const parsedRequest = jsonRpcRequestSchema.safeParse(body)
|
||||
if (isJsonRpcResponse(body)) {
|
||||
const responseSession = resolveSession(context, token)
|
||||
if (!responseSession) return true
|
||||
context.state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "MCP_TRANSPORT",
|
||||
direction: "inbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Accepted a syntactically valid JSON-RPC response message",
|
||||
})
|
||||
response.writeHead(202, { "cache-control": "no-store" })
|
||||
response.end()
|
||||
return true
|
||||
}
|
||||
if (!parsedRequest.success) {
|
||||
sendRpc(context, jsonRpcError(null, -32600, "Invalid Request", { issues: parsedRequest.error.issues.map((issue) => issue.message) }))
|
||||
return true
|
||||
}
|
||||
const rpc = parsedRequest.data
|
||||
|
||||
if (rpc.method === "initialize") {
|
||||
if (rpc.id === undefined) {
|
||||
response.writeHead(202, { "cache-control": "no-store" })
|
||||
response.end()
|
||||
return true
|
||||
}
|
||||
handleInitialize(context, rpc, token)
|
||||
return true
|
||||
}
|
||||
|
||||
const session = resolveSession(context, token)
|
||||
if (!session) return true
|
||||
|
||||
if (rpc.method === "notifications/initialized") {
|
||||
if (rpc.id !== undefined) {
|
||||
sendRpc(context, jsonRpcError(rpc.id, -32600, "notifications/initialized must not include a JSON-RPC id"))
|
||||
return true
|
||||
}
|
||||
if (faultApplies(context, "reject-initialized")) {
|
||||
emitFault(context, "Rejected notifications/initialized")
|
||||
sendJson(response, 400, { error: "initialized_notification_rejected" })
|
||||
return true
|
||||
}
|
||||
session.initialized = true
|
||||
response.writeHead(202, { "cache-control": "no-store" })
|
||||
response.end()
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "MCP_INITIALIZED",
|
||||
direction: "internal",
|
||||
kind: "lifecycle",
|
||||
outcome: "passed",
|
||||
summary: "Accepted notifications/initialized",
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
if (!session.initialized) {
|
||||
sendRpc(context, jsonRpcError(rpc.id ?? null, -32002, "MCP session is not initialized"))
|
||||
return true
|
||||
}
|
||||
|
||||
if (rpc.id === undefined) {
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "MCP_TRANSPORT",
|
||||
direction: "inbound",
|
||||
kind: "request",
|
||||
outcome: "passed",
|
||||
summary: "Accepted an unhandled JSON-RPC notification without emitting a response",
|
||||
details: { method: rpc.method },
|
||||
})
|
||||
response.writeHead(202, { "cache-control": "no-store" })
|
||||
response.end()
|
||||
return true
|
||||
}
|
||||
|
||||
if (rpc.method === "tools/list") {
|
||||
handleToolsList(context, rpc, session)
|
||||
return true
|
||||
}
|
||||
|
||||
if (rpc.method === "tools/call") {
|
||||
handleToolCall(context, rpc, session)
|
||||
return true
|
||||
}
|
||||
|
||||
sendRpc(context, jsonRpcError(rpc.id ?? null, -32601, `Unknown MCP method '${rpc.method}'`))
|
||||
return true
|
||||
}
|
||||
|
||||
function handleInitialize(context: McpRequestContext, rpc: JsonRpcRequest, token: AccessTokenRecord): void {
|
||||
const { state, scenario, profile, correlationId } = context
|
||||
const requestId = rpc.id ?? null
|
||||
if (requestId === null) {
|
||||
sendRpc(context, jsonRpcError(null, -32600, "initialize must be a JSON-RPC request with an id"))
|
||||
return
|
||||
}
|
||||
const params = initializeParamsSchema.safeParse(rpc.params)
|
||||
if (!params.success) {
|
||||
sendRpc(context, jsonRpcError(requestId, -32602, "Invalid initialize params"))
|
||||
return
|
||||
}
|
||||
if (faultApplies(context, "reject-version")) {
|
||||
emitFault(context, "Rejected MCP protocol version negotiation")
|
||||
sendRpc(
|
||||
context,
|
||||
jsonRpcError(requestId, -32602, "Unsupported MCP protocol version", { supportedVersions: profile.protocol.versions }),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
profile.protocol.versionNegotiation === "strict" &&
|
||||
!profile.protocol.versions.includes(params.data.protocolVersion)
|
||||
) {
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "MCP_VERSION",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "failed",
|
||||
summary: "Rejected an unsupported MCP protocol version with HTTP 400",
|
||||
details: {
|
||||
requestedVersion: params.data.protocolVersion,
|
||||
supportedVersions: profile.protocol.versions,
|
||||
},
|
||||
})
|
||||
sendJson(context.response, 400, {
|
||||
error: "unsupported_protocol_version",
|
||||
supportedVersions: profile.protocol.versions,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const negotiatedProtocolVersion = profile.protocol.versions.includes(params.data.protocolVersion)
|
||||
? params.data.protocolVersion
|
||||
: profile.protocol.versions[0]
|
||||
if (!negotiatedProtocolVersion) {
|
||||
sendRpc(context, jsonRpcError(requestId, -32603, "Server profile has no supported MCP protocol version"))
|
||||
return
|
||||
}
|
||||
|
||||
const sessionId = state.issueOpaque("mcp-session")
|
||||
state.putSession({
|
||||
sessionId,
|
||||
tokenFamilyId: token.familyId,
|
||||
operationNamespace: `${token.clientId}\u0000${token.subject}`,
|
||||
profileId: profile.id,
|
||||
protocolVersion: negotiatedProtocolVersion,
|
||||
scenarioRevision: scenario.revision,
|
||||
expiresAt: state.now() + sessionLifetimeMs,
|
||||
initialized: false,
|
||||
})
|
||||
const responseId = faultApplies(context, "malform-initialize") ? `${requestId}-mismatch` : requestId
|
||||
if (responseId !== requestId) emitFault(context, "Returned an initialize response with a mismatched JSON-RPC id")
|
||||
const responseWasConformant = sendRpc(
|
||||
context,
|
||||
jsonRpcResult(responseId, {
|
||||
protocolVersion: negotiatedProtocolVersion,
|
||||
capabilities: { tools: { listChanged: false } },
|
||||
serverInfo: { name: "openwork-enterprise-mcp-mock", version: "0.1.0" },
|
||||
instructions: `Synthetic ${profile.displayName} development server. No provider data or authority is present.`,
|
||||
}),
|
||||
{ "mcp-session-id": sessionId, "mcp-protocol-version": negotiatedProtocolVersion },
|
||||
)
|
||||
if (!responseWasConformant || responseId !== requestId) return
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "MCP_INITIALIZE",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Negotiated MCP protocol and created an isolated session",
|
||||
details: { protocolVersion: negotiatedProtocolVersion, profileId: profile.id },
|
||||
})
|
||||
}
|
||||
|
||||
function handleToolsList(context: McpRequestContext, rpc: JsonRpcRequest, session: SessionRecord): void {
|
||||
const requestId = rpc.id ?? null
|
||||
if (requestId === null) {
|
||||
sendRpc(context, jsonRpcError(null, -32600, "tools/list must be a JSON-RPC request with an id"))
|
||||
return
|
||||
}
|
||||
if (faultApplies(context, "per-user-403")) {
|
||||
emitFault(context, "Returned a per-user HTTP 403 before exposing the MCP tool catalog")
|
||||
sendJson(
|
||||
context.response,
|
||||
403,
|
||||
{ error: "provider_per_user_forbidden", message: "Authorization with MCP server failed — check your credentials and permissions" },
|
||||
{ "mcp-session-id": session.sessionId, "mcp-protocol-version": session.protocolVersion },
|
||||
)
|
||||
return
|
||||
}
|
||||
const params = listToolsParamsSchema.safeParse(rpc.params)
|
||||
if (!params.success) {
|
||||
sendRpc(context, jsonRpcError(requestId, -32602, "Invalid tools/list params"))
|
||||
return
|
||||
}
|
||||
const cursorText = params.data?.cursor
|
||||
const cursorMatch = cursorText ? /^page:(0|[1-9]\d*)$/.exec(cursorText) : null
|
||||
const offset = cursorText ? (cursorMatch ? Number(cursorMatch[1]) : Number.NaN) : 0
|
||||
if (!Number.isSafeInteger(offset) || offset < 0) {
|
||||
sendRpc(context, jsonRpcError(requestId, -32602, "Invalid catalog cursor"))
|
||||
return
|
||||
}
|
||||
|
||||
const emptyCatalogApplied = faultApplies(context, "empty-catalog")
|
||||
let tools = emptyCatalogApplied ? [] : context.profile.tools
|
||||
if (emptyCatalogApplied) emitFault(context, "Returned an empty MCP tool catalog")
|
||||
const page = tools.slice(offset, offset + context.scenario.protocol.pageSize).map((tool) => serializeTool(tool))
|
||||
let nextOffset = offset + context.scenario.protocol.pageSize
|
||||
let nextCursor: string | undefined = nextOffset < tools.length ? `page:${nextOffset}` : undefined
|
||||
|
||||
const repeatCursorApplied = Boolean(cursorText) && faultApplies(context, "repeat-cursor")
|
||||
if (repeatCursorApplied) {
|
||||
nextCursor = cursorText
|
||||
emitFault(context, "Repeated the MCP catalog cursor")
|
||||
}
|
||||
const duplicateToolApplied = offset > 0 && Boolean(tools[0]) && faultApplies(context, "duplicate-tool")
|
||||
if (duplicateToolApplied && tools[0]) {
|
||||
page.unshift(serializeTool(tools[0]))
|
||||
emitFault(context, "Repeated a tool name on a later MCP catalog page")
|
||||
}
|
||||
const invalidSchemaApplied = Boolean(page[0]) && faultApplies(context, "invalid-tool-schema")
|
||||
if (invalidSchemaApplied && page[0]) {
|
||||
page[0] = { ...page[0], inputSchema: { type: "object", properties: {}, required: "missing", additionalProperties: false } }
|
||||
emitFault(context, "Returned a tool with an invalid input schema")
|
||||
}
|
||||
|
||||
const responseWasConformant = sendRpc(
|
||||
context,
|
||||
jsonRpcResult(requestId, { tools: page, ...(nextCursor ? { nextCursor } : {}) }),
|
||||
{ "mcp-session-id": session.sessionId, "mcp-protocol-version": session.protocolVersion },
|
||||
)
|
||||
if (!responseWasConformant || emptyCatalogApplied || repeatCursorApplied || duplicateToolApplied || invalidSchemaApplied) return
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: "MCP_TOOL_DISCOVERY",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Returned one bounded MCP tool-catalog page",
|
||||
details: { toolCount: page.length, offset, hasNextPage: nextCursor !== undefined },
|
||||
})
|
||||
}
|
||||
|
||||
function serializeTool(tool: MockTool): Readonly<Record<string, unknown>> {
|
||||
return {
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: tool.kind === "read",
|
||||
destructiveHint: tool.kind === "mutation",
|
||||
idempotentHint: tool.kind === "read",
|
||||
openWorldHint: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function handleToolCall(context: McpRequestContext, rpc: JsonRpcRequest, session: SessionRecord): void {
|
||||
const requestId = rpc.id ?? null
|
||||
if (requestId === null) {
|
||||
sendRpc(context, jsonRpcError(null, -32600, "tools/call must be a JSON-RPC request with an id"))
|
||||
return
|
||||
}
|
||||
const params = callToolParamsSchema.safeParse(rpc.params)
|
||||
if (!params.success) {
|
||||
sendRpc(context, jsonRpcError(requestId, -32602, "Invalid tools/call params"))
|
||||
return
|
||||
}
|
||||
const tool = context.profile.tools.find((candidate) => candidate.name === params.data.name)
|
||||
if (!tool) {
|
||||
sendRpc(context, jsonRpcError(requestId, -32602, `Unknown tool '${params.data.name}'`))
|
||||
return
|
||||
}
|
||||
const argumentsResult = validateToolArguments(tool.inputSchema, params.data.arguments ?? {})
|
||||
if (!argumentsResult.success) {
|
||||
sendRpc(context, jsonRpcError(requestId, -32602, "Tool arguments do not match the declared input schema", { issues: argumentsResult.issues }))
|
||||
return
|
||||
}
|
||||
|
||||
if (tool.kind === "mutation") {
|
||||
const approved = argumentsResult.value.approved
|
||||
const idempotencyKey = argumentsResult.value.idempotency_key
|
||||
if (approved !== true || typeof idempotencyKey !== "string") {
|
||||
sendRpc(context, jsonRpcResult(requestId, toolError(context.state.issueOpaque("provider-request"), "MOCK_APPROVAL_REQUIRED", "Synthetic mutations require approved=true and an idempotency key", 400, "mock_approval_required")))
|
||||
return
|
||||
}
|
||||
const prepared = context.state.prepareOperation(session.operationNamespace, tool.name, idempotencyKey, argumentsResult.value)
|
||||
if (prepared.kind === "capacity") {
|
||||
sendRpc(context, jsonRpcResult(requestId, toolError(context.state.issueOpaque("provider-request"), "MUTATION_LEDGER_CAPACITY", "The bounded mutation ledger is full of unresolved operations; reconcile or reset explicitly before accepting another mutation", 507, "mutation_ledger_capacity")))
|
||||
return
|
||||
}
|
||||
if (prepared.kind === "conflict") {
|
||||
sendRpc(context, jsonRpcResult(requestId, toolError(context.state.issueOpaque("provider-request"), "IDEMPOTENCY_CONFLICT", "This idempotency key was already used with different operation arguments", 409, "idempotency_conflict")))
|
||||
return
|
||||
}
|
||||
if (prepared.kind === "reconcile") {
|
||||
sendRpc(context, jsonRpcResult(requestId, toolError(context.state.issueOpaque("provider-request"), "MUTATION_RECONCILIATION_REQUIRED", "The earlier mutation outcome is indeterminate; reconcile provider state before retrying", 409, "mutation_reconciliation_required")))
|
||||
return
|
||||
}
|
||||
if (prepared.kind === "duplicate") {
|
||||
sendRpc(context, jsonRpcResult(requestId, successResult({ operation: prepared.operation, duplicate: true })))
|
||||
return
|
||||
}
|
||||
const providerError = providerErrorResult(context)
|
||||
if (providerError) {
|
||||
context.state.operations.delete(prepared.operation.operationId)
|
||||
sendRpc(context, jsonRpcResult(requestId, providerError), {
|
||||
"mcp-session-id": session.sessionId,
|
||||
"mcp-protocol-version": session.protocolVersion,
|
||||
})
|
||||
return
|
||||
}
|
||||
const operation = prepared.operation
|
||||
const resultReference = stateReference(context)
|
||||
context.state.transitionOperation(operation.operationId, "committed", resultReference)
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: "PROVIDER_EXECUTION",
|
||||
direction: "internal",
|
||||
kind: "mutation",
|
||||
outcome: "completed",
|
||||
summary: "Committed a synthetic mutation to the in-memory ledger",
|
||||
details: { operationId: operation.operationId, tool: tool.name },
|
||||
})
|
||||
if (faultApplies(context, "commit-then-disconnect")) {
|
||||
context.state.transitionOperation(operation.operationId, "indeterminate", resultReference)
|
||||
emitFault(context, "Disconnected after the synthetic mutation committed")
|
||||
context.request.socket.destroy()
|
||||
return
|
||||
}
|
||||
const completed = context.state.transitionOperation(operation.operationId, "responded", resultReference)
|
||||
sendRpc(context, jsonRpcResult(requestId, successResult({ operation: completed })), {
|
||||
"mcp-session-id": session.sessionId,
|
||||
"mcp-protocol-version": session.protocolVersion,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const providerError = providerErrorResult(context)
|
||||
if (providerError) {
|
||||
sendRpc(context, jsonRpcResult(requestId, providerError), {
|
||||
"mcp-session-id": session.sessionId,
|
||||
"mcp-protocol-version": session.protocolVersion,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const responseWasConformant = sendRpc(context, jsonRpcResult(requestId, successResult(syntheticReadResult(context.profile.id, tool.name, argumentsResult.value, context.state.issueOpaque("provider-request")))), {
|
||||
"mcp-session-id": session.sessionId,
|
||||
"mcp-protocol-version": session.protocolVersion,
|
||||
})
|
||||
if (!responseWasConformant) return
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: "PROVIDER_EXECUTION",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Returned deterministic synthetic provider data",
|
||||
details: { profileId: context.profile.id, tool: tool.name },
|
||||
})
|
||||
}
|
||||
|
||||
function providerErrorResult(context: McpRequestContext): unknown | undefined {
|
||||
const fault = context.activeFault
|
||||
if (!fault) return undefined
|
||||
if (fault.effect === "provider-authorization-denial" && context.state.shouldApplyFault(fault, context.scenario)) {
|
||||
emitFault(context, "Returned a provider ACL denial as an MCP tool error")
|
||||
return toolError(context.state.issueOpaque("provider-request"), "PROVIDER_ACL_DENIED", "The synthetic provider denied this operation through roles or ACLs", 403, "provider_acl", false)
|
||||
}
|
||||
if (fault.effect === "provider-policy-denial" && context.state.shouldApplyFault(fault, context.scenario)) {
|
||||
emitFault(context, "Returned a provider governance denial as an MCP tool error")
|
||||
return toolError(context.state.issueOpaque("provider-request"), "PROVIDER_POLICY_DENIED", "A synthetic tenant policy or guardian blocked this operation", 403, "provider_policy", false)
|
||||
}
|
||||
if (fault.effect === "provider-throttle" && context.state.shouldApplyFault(fault, context.scenario)) {
|
||||
emitFault(context, "Returned synthetic provider throttling as an MCP tool error")
|
||||
return toolError(context.state.issueOpaque("provider-request"), "PROVIDER_THROTTLED", "The synthetic provider temporarily throttled this operation", 429, "provider_throttle", true, 3000)
|
||||
}
|
||||
if (fault.effect === "provider-unavailable" && context.state.shouldApplyFault(fault, context.scenario)) {
|
||||
emitFault(context, "Returned synthetic provider unavailability as an MCP tool error")
|
||||
return toolError(context.state.issueOpaque("provider-request"), "PROVIDER_UNAVAILABLE", "The synthetic provider is temporarily unavailable", 503, "provider_unavailable", true, 1000)
|
||||
}
|
||||
if (fault.effect === "duplicate-amplification" && context.state.shouldApplyFault(fault, context.scenario)) {
|
||||
const firstRequestId = context.state.issueOpaque("provider-request")
|
||||
const secondRequestId = context.state.issueOpaque("provider-request")
|
||||
emitFault(context, "Amplified one MCP tool call into duplicate upstream provider requests")
|
||||
return toolError(
|
||||
secondRequestId,
|
||||
"PROVIDER_DUPLICATE_REQUEST",
|
||||
"The gateway amplified one MCP tool call into duplicate requests",
|
||||
409,
|
||||
"provider_duplicate_request",
|
||||
false,
|
||||
undefined,
|
||||
{ duplicateRequestCount: 2, duplicateRequestIds: [firstRequestId, secondRequestId] },
|
||||
)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function toolError(
|
||||
providerRequestId: string,
|
||||
code: string,
|
||||
message: string,
|
||||
providerStatus: number,
|
||||
category: string,
|
||||
retryable = false,
|
||||
retryAfterMs?: number,
|
||||
evidence?: Readonly<Record<string, unknown>>,
|
||||
): unknown {
|
||||
const structuredContent = {
|
||||
providerStatus,
|
||||
category,
|
||||
requestId: providerRequestId,
|
||||
...evidence,
|
||||
retryAfterSeconds: retryAfterMs === undefined ? null : Math.ceil(retryAfterMs / 1000),
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
retryable,
|
||||
retryAfterMs: retryAfterMs ?? null,
|
||||
providerRequestId,
|
||||
},
|
||||
}
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: "text", text: JSON.stringify(structuredContent) }],
|
||||
structuredContent,
|
||||
}
|
||||
}
|
||||
|
||||
function successResult(value: unknown): unknown {
|
||||
return {
|
||||
isError: false,
|
||||
content: [{ type: "text", text: JSON.stringify(value) }],
|
||||
structuredContent: value,
|
||||
}
|
||||
}
|
||||
|
||||
function syntheticReadResult(
|
||||
profileId: string,
|
||||
toolName: string,
|
||||
argumentsValue: Readonly<Record<string, unknown>>,
|
||||
providerRequestId: string,
|
||||
): unknown {
|
||||
if (profileId === "servicenow-inbound-quickstart") {
|
||||
return {
|
||||
provider: "servicenow",
|
||||
tool: toolName,
|
||||
requestId: providerRequestId,
|
||||
records: [
|
||||
{
|
||||
number: "INC0000001",
|
||||
short_description: "Synthetic printer test incident",
|
||||
state: "In Progress",
|
||||
sys_id: "00000000000000000000000000000001",
|
||||
},
|
||||
],
|
||||
arguments: Object.keys(argumentsValue).sort(),
|
||||
}
|
||||
}
|
||||
return {
|
||||
provider: profileId === "synthetic-enterprise-oauth-mcp" ? "synthetic" : "microsoft",
|
||||
tool: toolName,
|
||||
requestId: providerRequestId,
|
||||
items: [
|
||||
{
|
||||
id: "00000000-0000-0000-0000-000000000001",
|
||||
displayName: "Synthetic Enterprise User",
|
||||
userPrincipalName: "synthetic.user@example.invalid",
|
||||
},
|
||||
],
|
||||
arguments: Object.keys(argumentsValue).sort(),
|
||||
}
|
||||
}
|
||||
|
||||
function isJsonRpcResponse(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return false
|
||||
const record = value as Record<string, unknown>
|
||||
if (record.jsonrpc !== "2.0" || "method" in record || !("id" in record)) return false
|
||||
if (!(typeof record.id === "string" || (typeof record.id === "number" && Number.isFinite(record.id)) || record.id === null)) {
|
||||
return false
|
||||
}
|
||||
const hasResult = Object.hasOwn(record, "result")
|
||||
const hasError = Object.hasOwn(record, "error")
|
||||
if (hasResult === hasError) return false
|
||||
if (!hasError) return true
|
||||
if (typeof record.error !== "object" || record.error === null || Array.isArray(record.error)) return false
|
||||
const error = record.error as Record<string, unknown>
|
||||
return typeof error.code === "number" && Number.isFinite(error.code) && typeof error.message === "string"
|
||||
}
|
||||
|
||||
function stateReference(context: McpRequestContext): string {
|
||||
return `synthetic:${context.state.issueOpaque("result")}`
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
import { createHash, randomUUID, timingSafeEqual } from "node:crypto"
|
||||
import type { IncomingMessage, ServerResponse } from "node:http"
|
||||
import { z } from "zod"
|
||||
import type { EnterpriseMcpScenario } from "../contracts/scenario.js"
|
||||
import type { ProviderProfile } from "../contracts/profile.js"
|
||||
import type { FaultDefinition } from "../contracts/fault.js"
|
||||
import type { InstanceState } from "../runtime/instance-state.js"
|
||||
import { readForm, readJson, redirect, sendJson, sendOAuthError } from "./http-utils.js"
|
||||
import { oauthRedirectUriSchema } from "../contracts/oauth.js"
|
||||
|
||||
interface OAuthRequestContext {
|
||||
readonly request: IncomingMessage
|
||||
readonly response: ServerResponse
|
||||
readonly url: URL
|
||||
readonly baseUrl: string
|
||||
readonly correlationId: string
|
||||
readonly scenario: EnterpriseMcpScenario
|
||||
readonly profile: ProviderProfile
|
||||
readonly state: InstanceState
|
||||
readonly activeFault: FaultDefinition | undefined
|
||||
}
|
||||
|
||||
const registrationRequestSchema = z.object({
|
||||
redirect_uris: z.array(oauthRedirectUriSchema).min(1).max(10),
|
||||
token_endpoint_auth_method: z.enum(["none", "client_secret_post"]).optional(),
|
||||
client_name: z.string().min(1).max(200).optional(),
|
||||
})
|
||||
|
||||
const pkceVerifierPattern = /^[A-Za-z0-9._~-]{43,128}$/
|
||||
const pkceS256ChallengePattern = /^[A-Za-z0-9_-]{43}$/
|
||||
const refreshTokenLifetimeMs = 30 * 24 * 60 * 60 * 1000
|
||||
|
||||
function safeEqual(left: string, right: string): boolean {
|
||||
const leftBuffer = Buffer.from(left)
|
||||
const rightBuffer = Buffer.from(right)
|
||||
return (
|
||||
leftBuffer.byteLength === rightBuffer.byteLength &&
|
||||
timingSafeEqual(Uint8Array.from(leftBuffer), Uint8Array.from(rightBuffer))
|
||||
)
|
||||
}
|
||||
|
||||
function pkceChallenge(verifier: string): string {
|
||||
return createHash("sha256").update(verifier).digest("base64url")
|
||||
}
|
||||
|
||||
function faultApplies(context: OAuthRequestContext, effect: FaultDefinition["effect"]): boolean {
|
||||
return context.activeFault?.effect === effect && context.state.shouldApplyFault(context.activeFault, context.scenario)
|
||||
}
|
||||
|
||||
function emitFault(context: OAuthRequestContext, summary: string): void {
|
||||
const fault = context.activeFault
|
||||
if (!fault) return
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: fault.phase,
|
||||
direction: "outbound",
|
||||
kind: "fault",
|
||||
outcome: "applied",
|
||||
summary,
|
||||
details: { faultId: fault.id, category: fault.category },
|
||||
})
|
||||
}
|
||||
|
||||
function trailingDotAuthorityUrl(baseUrl: string): string {
|
||||
const url = new URL(baseUrl)
|
||||
if (!url.hostname || url.hostname.endsWith(".")) return baseUrl
|
||||
const port = url.port ? `:${url.port}` : ""
|
||||
return `${url.protocol}//${url.hostname}.${port}`
|
||||
}
|
||||
|
||||
function sendInvalidClient(context: OAuthRequestContext): void {
|
||||
const { response, profile, scenario, state, correlationId } = context
|
||||
if (profile.provider === "microsoft") {
|
||||
const traceId = randomUUID()
|
||||
const timestamp = new Date(state.now()).toISOString().replace("T", " ").replace(/\.\d{3}Z$/, "Z")
|
||||
sendJson(response, 401, {
|
||||
error: "invalid_client",
|
||||
error_description: `AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value, not the client secret ID, for a secret added to app '${scenario.oauth.clientId}'. Trace ID: ${traceId} Correlation ID: ${correlationId} Timestamp: ${timestamp}`,
|
||||
error_codes: [7_000_215],
|
||||
timestamp,
|
||||
trace_id: traceId,
|
||||
correlation_id: correlationId,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (profile.provider === "servicenow") {
|
||||
sendOAuthError(
|
||||
response,
|
||||
401,
|
||||
"invalid_client",
|
||||
"Client authentication failed. Verify the client ID and client secret configured for this ServiceNow OAuth application.",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
sendOAuthError(response, 401, "invalid_client", "The synthetic OAuth client was rejected")
|
||||
}
|
||||
|
||||
function sendTokenError(
|
||||
context: OAuthRequestContext,
|
||||
status: number,
|
||||
error: string,
|
||||
errorDescription: string,
|
||||
slackError: "invalid_code" | "invalid_refresh_token",
|
||||
): void {
|
||||
if (context.profile.oauth.tokenResponseStyle === "slack-user") {
|
||||
sendJson(context.response, 200, { ok: false, error: slackError })
|
||||
return
|
||||
}
|
||||
sendOAuthError(context.response, status, error, errorDescription)
|
||||
}
|
||||
|
||||
export async function handleOAuthRequest(context: OAuthRequestContext): Promise<boolean> {
|
||||
const { request, response, url, baseUrl, scenario, profile, state, correlationId } = context
|
||||
const mcpUrl = new URL(profile.endpointPath, baseUrl).href
|
||||
const resourceMetadataPath = `/.well-known/oauth-protected-resource${profile.endpointPath}`
|
||||
|
||||
if (request.method === "GET" && (url.pathname === resourceMetadataPath || url.pathname === "/.well-known/oauth-protected-resource")) {
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_RESOURCE_DISCOVERY",
|
||||
direction: "inbound",
|
||||
kind: "request",
|
||||
outcome: "started",
|
||||
summary: "Protected-resource metadata requested",
|
||||
details: { path: url.pathname },
|
||||
})
|
||||
if (faultApplies(context, "malformed-resource-metadata")) {
|
||||
emitFault(context, "Returned mismatched protected-resource metadata")
|
||||
sendJson(response, 200, { resource: `${mcpUrl}/wrong-resource`, authorization_servers: [baseUrl] })
|
||||
return true
|
||||
}
|
||||
const authorizationServers = faultApplies(context, "trailing-dot-url")
|
||||
? [trailingDotAuthorityUrl(baseUrl)]
|
||||
: [baseUrl]
|
||||
if (authorizationServers[0] !== baseUrl) emitFault(context, "Published an authorization-server URL with a stray trailing-dot host")
|
||||
sendJson(response, 200, {
|
||||
resource: mcpUrl,
|
||||
authorization_servers: authorizationServers,
|
||||
scopes_supported: scenario.oauth.requiredResourceScopes,
|
||||
bearer_methods_supported: ["header"],
|
||||
})
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_RESOURCE_DISCOVERY",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Returned coherent protected-resource metadata",
|
||||
details: { resourceOrigin: new URL(mcpUrl).origin, scopeCount: scenario.oauth.authorizationScopes.length },
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
if (
|
||||
request.method === "GET" &&
|
||||
(url.pathname === "/.well-known/oauth-authorization-server" || url.pathname === "/.well-known/openid-configuration")
|
||||
) {
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_ISSUER_DISCOVERY",
|
||||
direction: "inbound",
|
||||
kind: "request",
|
||||
outcome: "started",
|
||||
summary: "Authorization-server metadata requested",
|
||||
})
|
||||
const issuer = faultApplies(context, "issuer-mismatch") ? `${baseUrl}/mismatched-issuer` : baseUrl
|
||||
if (issuer !== baseUrl) emitFault(context, "Published an intentionally mismatched OAuth issuer")
|
||||
const pkceMethods = faultApplies(context, "omit-pkce-s256") ? ["plain"] : ["S256"]
|
||||
if (!pkceMethods.includes("S256")) emitFault(context, "Omitted PKCE S256 from authorization-server metadata")
|
||||
sendJson(response, 200, {
|
||||
issuer,
|
||||
authorization_endpoint: new URL(profile.oauth.authorizationPath, baseUrl).href,
|
||||
token_endpoint: new URL(profile.oauth.tokenPath, baseUrl).href,
|
||||
registration_endpoint:
|
||||
scenario.oauth.registration === "dynamic" && profile.oauth.registrationPath
|
||||
? new URL(profile.oauth.registrationPath, baseUrl).href
|
||||
: undefined,
|
||||
revocation_endpoint: new URL(profile.oauth.revocationPath, baseUrl).href,
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code", "refresh_token"],
|
||||
code_challenge_methods_supported: pkceMethods,
|
||||
token_endpoint_auth_methods_supported: profile.oauth.clientAuthenticationMethods,
|
||||
scopes_supported: scenario.oauth.authorizationScopes,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
if (request.method === "POST" && profile.oauth.registrationPath && url.pathname === profile.oauth.registrationPath) {
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_CLIENT_REGISTRATION",
|
||||
direction: "inbound",
|
||||
kind: "request",
|
||||
outcome: "started",
|
||||
summary: "Dynamic client registration requested",
|
||||
})
|
||||
if (scenario.oauth.registration !== "dynamic" || faultApplies(context, "reject-registration")) {
|
||||
if (context.activeFault?.effect === "reject-registration") emitFault(context, "Rejected dynamic client registration")
|
||||
sendJson(response, 404, { error: "registration_not_supported" })
|
||||
return true
|
||||
}
|
||||
const registration = registrationRequestSchema.parse(await readJson(request))
|
||||
const tokenEndpointAuthMethod = registration.token_endpoint_auth_method ?? "none"
|
||||
if (!profile.oauth.clientAuthenticationMethods.includes(tokenEndpointAuthMethod)) {
|
||||
sendJson(response, 400, { error: "invalid_client_metadata", error_description: "Unsupported token endpoint authentication method" })
|
||||
return true
|
||||
}
|
||||
const clientId = state.issueOpaque("client")
|
||||
const clientSecret = tokenEndpointAuthMethod === "client_secret_post" ? state.issueOpaque("client-secret") : ""
|
||||
state.putClient({
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUris: registration.redirect_uris,
|
||||
tokenEndpointAuthMethod,
|
||||
createdAt: state.now(),
|
||||
expiresAt: state.now() + 3_600_000,
|
||||
})
|
||||
sendJson(response, 201, {
|
||||
client_id: clientId,
|
||||
...(clientSecret ? { client_secret: clientSecret } : {}),
|
||||
redirect_uris: registration.redirect_uris,
|
||||
token_endpoint_auth_method: tokenEndpointAuthMethod,
|
||||
})
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_CLIENT_REGISTRATION",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Registered a synthetic OAuth client",
|
||||
details: { clientIdHash: createHash("sha256").update(clientId).digest("hex"), redirectCount: registration.redirect_uris.length },
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
if (request.method === "GET" && url.pathname === profile.oauth.authorizationPath) {
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_USER_OR_WORKLOAD",
|
||||
direction: "inbound",
|
||||
kind: "request",
|
||||
outcome: "started",
|
||||
summary: "Synthetic authorization requested",
|
||||
})
|
||||
const clientId = url.searchParams.get("client_id") ?? ""
|
||||
const responseType = url.searchParams.get("response_type") ?? ""
|
||||
const redirectUri = url.searchParams.get("redirect_uri") ?? ""
|
||||
const codeChallenge = url.searchParams.get("code_challenge") ?? ""
|
||||
const codeChallengeMethod = url.searchParams.get("code_challenge_method") ?? ""
|
||||
const resource = url.searchParams.get("resource") ?? ""
|
||||
const oauthState = url.searchParams.get("state") ?? ""
|
||||
const scope = url.searchParams.get("scope") ?? ""
|
||||
const requestedScopes = scope.split(" ").filter(Boolean)
|
||||
const client = state.clients.get(clientId)
|
||||
if (
|
||||
responseType !== "code" ||
|
||||
!client ||
|
||||
!client.redirectUris.includes(redirectUri) ||
|
||||
resource !== mcpUrl ||
|
||||
codeChallengeMethod !== "S256" ||
|
||||
!pkceS256ChallengePattern.test(codeChallenge)
|
||||
) {
|
||||
sendOAuthError(response, 400, "invalid_request", "Client, redirect URI, resource, and PKCE S256 must match the active scenario")
|
||||
return true
|
||||
}
|
||||
if (faultApplies(context, "redirect-uri-whitelist")) {
|
||||
emitFault(context, "Rejected OAuth authorization because the redirect URI is not allowlisted")
|
||||
sendOAuthError(response, 400, "invalid_request", "redirect URI is not an allowed destination")
|
||||
return true
|
||||
}
|
||||
if (faultApplies(context, "dcr-required")) {
|
||||
emitFault(context, "Rejected manual OAuth authorization because dynamic client registration is required")
|
||||
sendOAuthError(
|
||||
response,
|
||||
400,
|
||||
"dynamic_client_registration_required",
|
||||
"The MCP connection failed before OpenWork could complete the protocol lifecycle. Dynamic client registration is required before this gateway accepts OAuth authorization.",
|
||||
)
|
||||
return true
|
||||
}
|
||||
if (
|
||||
requestedScopes.length === 0 ||
|
||||
requestedScopes.some((requestedScope) => !scenario.oauth.authorizationScopes.includes(requestedScope)) ||
|
||||
scenario.oauth.requiredResourceScopes.some((requiredScope) => !requestedScopes.includes(requiredScope))
|
||||
) {
|
||||
sendOAuthError(response, 400, "invalid_scope", "Requested scopes must be a non-empty subset of the active scenario")
|
||||
return true
|
||||
}
|
||||
const code = state.issueOpaque("authorization-code")
|
||||
state.putAuthorizationCode({
|
||||
code,
|
||||
clientId,
|
||||
redirectUri,
|
||||
codeChallenge,
|
||||
resource,
|
||||
scopes: requestedScopes,
|
||||
expiresAt: state.now() + 60_000,
|
||||
})
|
||||
const destination = new URL(redirectUri)
|
||||
destination.searchParams.set("code", code)
|
||||
destination.searchParams.set("state", oauthState)
|
||||
redirect(response, destination.href)
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_USER_OR_WORKLOAD",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Synthetic user authorization completed",
|
||||
details: { redirectOrigin: destination.origin },
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
if (request.method === "POST" && url.pathname === profile.oauth.tokenPath) {
|
||||
state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "AUTH_TOKEN_ACQUISITION",
|
||||
direction: "inbound",
|
||||
kind: "request",
|
||||
outcome: "started",
|
||||
summary: "OAuth token exchange requested",
|
||||
})
|
||||
const form = await readForm(request)
|
||||
const clientId = form.get("client_id") ?? ""
|
||||
const clientSecret = form.get("client_secret") ?? ""
|
||||
const client = state.clients.get(clientId)
|
||||
const clientAuthenticationValid =
|
||||
client?.tokenEndpointAuthMethod === "none"
|
||||
? clientSecret.length === 0
|
||||
: client?.tokenEndpointAuthMethod === "client_secret_post" && safeEqual(client.clientSecret, clientSecret)
|
||||
if (faultApplies(context, "reject-client") || !client || !clientAuthenticationValid) {
|
||||
if (context.activeFault?.effect === "reject-client") emitFault(context, "Rejected the OAuth client during token exchange")
|
||||
if (profile.oauth.tokenResponseStyle === "slack-user") {
|
||||
sendJson(response, 200, { ok: false, error: "bad_client_secret" })
|
||||
} else {
|
||||
sendInvalidClient(context)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const grantType = form.get("grant_type") ?? ""
|
||||
if (grantType === "authorization_code") {
|
||||
const code = form.get("code") ?? ""
|
||||
const codeRecord = state.authorizationCodes.get(code)
|
||||
const verifier = form.get("code_verifier") ?? ""
|
||||
if (faultApplies(context, "per-connector-redirect")) {
|
||||
emitFault(context, "Rejected token exchange because the provider expected a per-connector redirect URI")
|
||||
sendOAuthError(
|
||||
response,
|
||||
400,
|
||||
"invalid_grant",
|
||||
"External MCP connect callback token exchange failed: the provider expected a per-connector redirect URI.",
|
||||
)
|
||||
return true
|
||||
}
|
||||
const invalidGrant =
|
||||
faultApplies(context, "reject-grant") ||
|
||||
!codeRecord ||
|
||||
codeRecord.expiresAt < state.now() ||
|
||||
codeRecord.clientId !== clientId ||
|
||||
codeRecord.redirectUri !== (form.get("redirect_uri") ?? "") ||
|
||||
codeRecord.resource !== (form.get("resource") ?? "") ||
|
||||
!pkceVerifierPattern.test(verifier) ||
|
||||
!safeEqual(codeRecord.codeChallenge, pkceChallenge(verifier))
|
||||
if (invalidGrant) {
|
||||
if (context.activeFault?.effect === "reject-grant") emitFault(context, "Rejected the authorization grant during token exchange")
|
||||
sendTokenError(
|
||||
context,
|
||||
400,
|
||||
"invalid_grant",
|
||||
"The authorization code or PKCE verifier was rejected",
|
||||
"invalid_code",
|
||||
)
|
||||
return true
|
||||
}
|
||||
state.authorizationCodes.delete(code)
|
||||
issueTokenResponse(context, clientId, codeRecord.resource, codeRecord.scopes)
|
||||
return true
|
||||
}
|
||||
|
||||
if (grantType === "refresh_token") {
|
||||
const refreshToken = form.get("refresh_token") ?? ""
|
||||
const existing = state.refreshTokens.get(refreshToken)
|
||||
if (faultApplies(context, "refresh-expired")) {
|
||||
emitFault(context, "Rejected refresh-token continuity because the credential expired")
|
||||
sendTokenError(
|
||||
context,
|
||||
400,
|
||||
"invalid_grant",
|
||||
"The refresh token expired; reconnect the provider account before retrying.",
|
||||
"invalid_refresh_token",
|
||||
)
|
||||
return true
|
||||
}
|
||||
if (!existing || existing.clientId !== clientId) {
|
||||
sendTokenError(
|
||||
context,
|
||||
400,
|
||||
"invalid_grant",
|
||||
"The synthetic refresh token was rejected",
|
||||
"invalid_refresh_token",
|
||||
)
|
||||
return true
|
||||
}
|
||||
revokeTokenFamily(state, existing.familyId)
|
||||
issueTokenResponse(context, clientId, existing.resource, existing.scopes, existing.familyId)
|
||||
return true
|
||||
}
|
||||
|
||||
sendOAuthError(response, 400, "unsupported_grant_type", "Only authorization_code and refresh_token are supported")
|
||||
return true
|
||||
}
|
||||
|
||||
if (request.method === "POST" && url.pathname === profile.oauth.revocationPath) {
|
||||
const form = await readForm(request)
|
||||
const tokenValue = form.get("token") ?? ""
|
||||
const accessToken = state.tokens.get(tokenValue)
|
||||
const refreshToken = state.refreshTokens.get(tokenValue)
|
||||
const targetClientId = accessToken?.clientId ?? refreshToken?.clientId
|
||||
const clientId = form.get("client_id") ?? ""
|
||||
const clientSecret = form.get("client_secret") ?? ""
|
||||
const client = state.clients.get(clientId)
|
||||
const clientAuthenticationValid =
|
||||
client?.tokenEndpointAuthMethod === "none"
|
||||
? clientSecret.length === 0
|
||||
: client?.tokenEndpointAuthMethod === "client_secret_post" && safeEqual(client.clientSecret, clientSecret)
|
||||
if (!client || !clientAuthenticationValid || (targetClientId !== undefined && targetClientId !== clientId)) {
|
||||
sendInvalidClient(context)
|
||||
return true
|
||||
}
|
||||
const familyId = accessToken?.familyId ?? refreshToken?.familyId
|
||||
if (familyId) revokeTokenFamily(state, familyId)
|
||||
response.writeHead(200, { "cache-control": "no-store" })
|
||||
response.end()
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function issueTokenResponse(
|
||||
context: OAuthRequestContext,
|
||||
clientId: string,
|
||||
resource: string,
|
||||
scopes: readonly string[],
|
||||
existingFamilyId?: string,
|
||||
): void {
|
||||
const slackStyle = context.profile.oauth.tokenResponseStyle === "slack-user"
|
||||
const accessToken = context.state.issueOpaque(slackStyle ? "xoxp" : "access-token")
|
||||
const refreshToken = context.state.issueOpaque(slackStyle ? "xoxe-1" : "refresh-token")
|
||||
const familyId = existingFamilyId ?? context.state.issueOpaque("token-family")
|
||||
const expiresIn = slackStyle ? 43_200 : 3_600
|
||||
context.state.putToken({
|
||||
accessToken,
|
||||
familyId,
|
||||
clientId,
|
||||
resource,
|
||||
scopes,
|
||||
subject: "synthetic-enterprise-user@example.invalid",
|
||||
expiresAt: context.state.now() + expiresIn * 1_000,
|
||||
})
|
||||
context.state.putRefreshToken({
|
||||
refreshToken,
|
||||
familyId,
|
||||
clientId,
|
||||
resource,
|
||||
scopes,
|
||||
subject: "synthetic-enterprise-user@example.invalid",
|
||||
expiresAt: context.state.now() + refreshTokenLifetimeMs,
|
||||
})
|
||||
sendJson(
|
||||
context.response,
|
||||
200,
|
||||
slackStyle
|
||||
? {
|
||||
ok: true,
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
token_type: "user",
|
||||
expires_in: expiresIn,
|
||||
scope: scopes.join(" "),
|
||||
}
|
||||
: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
token_type: "Bearer",
|
||||
expires_in: expiresIn,
|
||||
scope: scopes.join(" "),
|
||||
},
|
||||
)
|
||||
context.state.emit({
|
||||
correlationId: context.correlationId,
|
||||
scenario: context.scenario,
|
||||
phase: "AUTH_TOKEN_ACQUISITION",
|
||||
direction: "outbound",
|
||||
kind: "response",
|
||||
outcome: "passed",
|
||||
summary: "Issued bounded synthetic OAuth tokens",
|
||||
details: { scopeCount: scopes.length, resourceOrigin: new URL(resource).origin },
|
||||
})
|
||||
}
|
||||
|
||||
function revokeTokenFamily(state: InstanceState, familyId: string): void {
|
||||
for (const [accessToken, record] of state.tokens) {
|
||||
if (record.familyId === familyId) state.tokens.delete(accessToken)
|
||||
}
|
||||
for (const [refreshToken, record] of state.refreshTokens) {
|
||||
if (record.familyId === familyId) state.refreshTokens.delete(refreshToken)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
import type { EnterpriseMcpScenario } from "../contracts/scenario.js"
|
||||
import type {
|
||||
MutationOperationSummary,
|
||||
RuntimeSnapshot,
|
||||
SafeTraceDetail,
|
||||
SafeTraceEvent,
|
||||
EnterpriseMcpMockEnvironment,
|
||||
} from "../contracts/runtime.js"
|
||||
import type { HandshakePhase } from "../contracts/phases.js"
|
||||
import type { ProviderProfile } from "../contracts/profile.js"
|
||||
import type { FaultDefinition } from "../contracts/fault.js"
|
||||
import { sanitizeTraceDetails, sha256 } from "../observability/redaction.js"
|
||||
import { deepFreeze } from "../immutability.js"
|
||||
|
||||
export interface OAuthClientRecord {
|
||||
readonly clientId: string
|
||||
readonly clientSecret: string
|
||||
readonly redirectUris: readonly string[]
|
||||
readonly tokenEndpointAuthMethod: "none" | "client_secret_post"
|
||||
readonly createdAt: number
|
||||
readonly expiresAt: number | null
|
||||
}
|
||||
|
||||
export interface AuthorizationCodeRecord {
|
||||
readonly code: string
|
||||
readonly clientId: string
|
||||
readonly redirectUri: string
|
||||
readonly codeChallenge: string
|
||||
readonly resource: string
|
||||
readonly scopes: readonly string[]
|
||||
readonly expiresAt: number
|
||||
}
|
||||
|
||||
export interface AccessTokenRecord {
|
||||
readonly accessToken: string
|
||||
readonly familyId: string
|
||||
readonly clientId: string
|
||||
readonly resource: string
|
||||
readonly scopes: readonly string[]
|
||||
readonly subject: string
|
||||
readonly expiresAt: number
|
||||
}
|
||||
|
||||
export interface RefreshTokenRecord {
|
||||
readonly refreshToken: string
|
||||
readonly familyId: string
|
||||
readonly clientId: string
|
||||
readonly resource: string
|
||||
readonly scopes: readonly string[]
|
||||
readonly subject: string
|
||||
readonly expiresAt: number
|
||||
}
|
||||
|
||||
export interface SessionRecord {
|
||||
readonly sessionId: string
|
||||
readonly tokenFamilyId: string
|
||||
readonly operationNamespace: string
|
||||
readonly profileId: string
|
||||
readonly protocolVersion: string
|
||||
readonly scenarioRevision: number
|
||||
readonly expiresAt: number
|
||||
initialized: boolean
|
||||
}
|
||||
|
||||
interface MutableOperation {
|
||||
readonly operationId: string
|
||||
readonly idempotencyKeyHash: string
|
||||
readonly namespaceHash: string
|
||||
readonly tool: string
|
||||
readonly argumentsHash: string
|
||||
state: "prepared" | "committed" | "responded" | "indeterminate"
|
||||
resultReference: string | null
|
||||
readonly createdAt: number
|
||||
}
|
||||
|
||||
export type PrepareOperationResult =
|
||||
| { readonly kind: "prepared"; readonly operation: MutationOperationSummary }
|
||||
| { readonly kind: "duplicate"; readonly operation: MutationOperationSummary }
|
||||
| { readonly kind: "conflict"; readonly operation: MutationOperationSummary }
|
||||
| { readonly kind: "reconcile"; readonly operation: MutationOperationSummary }
|
||||
| { readonly kind: "capacity" }
|
||||
|
||||
interface EmitEventInput {
|
||||
readonly correlationId: string
|
||||
readonly scenario: EnterpriseMcpScenario
|
||||
readonly phase: HandshakePhase
|
||||
readonly direction: SafeTraceEvent["direction"]
|
||||
readonly kind: SafeTraceEvent["kind"]
|
||||
readonly outcome: SafeTraceEvent["outcome"]
|
||||
readonly summary: string
|
||||
readonly details?: Readonly<Record<string, SafeTraceDetail>>
|
||||
}
|
||||
|
||||
const maximumEventCount = 500
|
||||
const maximumClientCount = 100
|
||||
const maximumAuthorizationCodeCount = 100
|
||||
const maximumTokenCount = 100
|
||||
const maximumSessionCount = 100
|
||||
const maximumOperationCount = 1000
|
||||
const maximumFaultCounterCount = 100
|
||||
const operationTtlMs = 86_400_000
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function canonicalJson(value: unknown): string {
|
||||
if (value === null) return "null"
|
||||
if (typeof value === "string" || typeof value === "boolean" || typeof value === "number") return JSON.stringify(value)
|
||||
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`
|
||||
if (isRecord(value)) {
|
||||
return `{${Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
|
||||
.join(",")}}`
|
||||
}
|
||||
return JSON.stringify(String(value))
|
||||
}
|
||||
|
||||
export class InstanceState {
|
||||
readonly instanceId: string
|
||||
readonly clients = new Map<string, OAuthClientRecord>()
|
||||
readonly authorizationCodes = new Map<string, AuthorizationCodeRecord>()
|
||||
readonly tokens = new Map<string, AccessTokenRecord>()
|
||||
readonly refreshTokens = new Map<string, RefreshTokenRecord>()
|
||||
readonly sessions = new Map<string, SessionRecord>()
|
||||
readonly operations = new Map<string, MutableOperation>()
|
||||
readonly faultCounters = new Map<string, number>()
|
||||
private readonly traceEvents: SafeTraceEvent[] = []
|
||||
private runtimeStatus: RuntimeSnapshot["status"] = "idle"
|
||||
private runtimeBaseUrl: string | null = null
|
||||
|
||||
constructor(
|
||||
private currentScenario: EnterpriseMcpScenario,
|
||||
private currentProfile: ProviderProfile,
|
||||
private readonly knownSecrets: readonly string[],
|
||||
private readonly environment: EnterpriseMcpMockEnvironment,
|
||||
instanceId?: string,
|
||||
) {
|
||||
this.instanceId = instanceId ?? environment.randomId()
|
||||
this.currentScenario = deepFreeze(currentScenario)
|
||||
this.currentProfile = deepFreeze(currentProfile)
|
||||
}
|
||||
|
||||
get scenario(): EnterpriseMcpScenario {
|
||||
return this.currentScenario
|
||||
}
|
||||
|
||||
get profile(): ProviderProfile {
|
||||
return this.currentProfile
|
||||
}
|
||||
|
||||
get status(): RuntimeSnapshot["status"] {
|
||||
return this.runtimeStatus
|
||||
}
|
||||
|
||||
get baseUrl(): string | null {
|
||||
return this.runtimeBaseUrl
|
||||
}
|
||||
|
||||
setRuntime(status: RuntimeSnapshot["status"], baseUrl: string | null): void {
|
||||
this.runtimeStatus = status
|
||||
this.runtimeBaseUrl = baseUrl
|
||||
}
|
||||
|
||||
replaceScenario(scenario: EnterpriseMcpScenario, profile: ProviderProfile): void {
|
||||
this.currentScenario = deepFreeze(scenario)
|
||||
this.currentProfile = deepFreeze(profile)
|
||||
this.clearEphemeralState()
|
||||
}
|
||||
|
||||
clearEphemeralState(): void {
|
||||
this.clearConnectionState()
|
||||
this.operations.clear()
|
||||
this.faultCounters.clear()
|
||||
}
|
||||
|
||||
clearConnectionState(): void {
|
||||
this.clients.clear()
|
||||
this.authorizationCodes.clear()
|
||||
this.tokens.clear()
|
||||
this.refreshTokens.clear()
|
||||
this.sessions.clear()
|
||||
}
|
||||
|
||||
inheritEstablishedOAuthAuthority(source: InstanceState): void {
|
||||
this.clearEphemeralState()
|
||||
this.clearEvents()
|
||||
source.maintainBounds(this.environment.now())
|
||||
for (const [clientId, client] of source.clients) this.clients.set(clientId, client)
|
||||
for (const [accessToken, token] of source.tokens) {
|
||||
if (this.clients.has(token.clientId)) this.tokens.set(accessToken, token)
|
||||
}
|
||||
for (const [refreshToken, token] of source.refreshTokens) {
|
||||
if (this.clients.has(token.clientId)) this.refreshTokens.set(refreshToken, token)
|
||||
}
|
||||
this.maintainBounds(this.environment.now())
|
||||
}
|
||||
|
||||
maintainBounds(now = this.environment.now()): void {
|
||||
for (const [key, client] of this.clients) {
|
||||
if (client.expiresAt !== null && client.expiresAt < now) this.clients.delete(key)
|
||||
}
|
||||
for (const [key, code] of this.authorizationCodes) if (code.expiresAt < now) this.authorizationCodes.delete(key)
|
||||
for (const [key, token] of this.tokens) if (token.expiresAt < now) this.tokens.delete(key)
|
||||
for (const [key, token] of this.refreshTokens) if (token.expiresAt < now) this.refreshTokens.delete(key)
|
||||
for (const [key, session] of this.sessions) if (session.expiresAt < now) this.sessions.delete(key)
|
||||
for (const [key, operation] of this.operations) {
|
||||
if (operation.state === "responded" && operation.createdAt + operationTtlMs < now) this.operations.delete(key)
|
||||
}
|
||||
this.trimOldest(this.clients, maximumClientCount)
|
||||
this.trimOldest(this.authorizationCodes, maximumAuthorizationCodeCount)
|
||||
this.trimOldest(this.tokens, maximumTokenCount)
|
||||
this.trimOldest(this.refreshTokens, maximumTokenCount)
|
||||
this.trimOldest(this.sessions, maximumSessionCount)
|
||||
this.trimRespondedOperations(maximumOperationCount)
|
||||
this.trimOldest(this.faultCounters, maximumFaultCounterCount)
|
||||
}
|
||||
|
||||
putClient(client: OAuthClientRecord): void {
|
||||
this.clients.set(client.clientId, client)
|
||||
this.maintainBounds()
|
||||
}
|
||||
|
||||
putAuthorizationCode(code: AuthorizationCodeRecord): void {
|
||||
this.authorizationCodes.set(code.code, code)
|
||||
this.maintainBounds()
|
||||
}
|
||||
|
||||
putToken(token: AccessTokenRecord): void {
|
||||
this.tokens.set(token.accessToken, token)
|
||||
this.maintainBounds()
|
||||
}
|
||||
|
||||
putRefreshToken(token: RefreshTokenRecord): void {
|
||||
this.refreshTokens.set(token.refreshToken, token)
|
||||
this.maintainBounds()
|
||||
}
|
||||
|
||||
putSession(session: SessionRecord): void {
|
||||
this.sessions.set(session.sessionId, session)
|
||||
this.maintainBounds()
|
||||
}
|
||||
|
||||
clearEvents(): void {
|
||||
this.traceEvents.splice(0, this.traceEvents.length)
|
||||
}
|
||||
|
||||
issueOpaque(prefix: string): string {
|
||||
return this.environment.opaqueValue(prefix)
|
||||
}
|
||||
|
||||
now(): number {
|
||||
return this.environment.now()
|
||||
}
|
||||
|
||||
emit(input: EmitEventInput): SafeTraceEvent {
|
||||
const event: SafeTraceEvent = deepFreeze({
|
||||
id: this.environment.randomId(),
|
||||
occurredAt: new Date(this.environment.now()).toISOString(),
|
||||
correlationId: input.correlationId,
|
||||
revision: input.scenario.revision,
|
||||
phase: input.phase,
|
||||
direction: input.direction,
|
||||
kind: input.kind,
|
||||
outcome: input.outcome,
|
||||
summary: input.summary,
|
||||
details: sanitizeTraceDetails(input.details ?? {}, this.knownSecrets),
|
||||
})
|
||||
this.traceEvents.push(event)
|
||||
if (this.traceEvents.length > maximumEventCount) this.traceEvents.splice(0, this.traceEvents.length - maximumEventCount)
|
||||
return event
|
||||
}
|
||||
|
||||
events(): readonly SafeTraceEvent[] {
|
||||
return deepFreeze([...this.traceEvents])
|
||||
}
|
||||
|
||||
shouldApplyFault(definition: FaultDefinition, scenario: EnterpriseMcpScenario): boolean {
|
||||
const active = scenario.activeFault
|
||||
if (!active || active.id !== definition.id) return false
|
||||
const counterKey = `${scenario.revision}:${definition.id}`
|
||||
const nextCount = (this.faultCounters.get(counterKey) ?? 0) + 1
|
||||
this.faultCounters.set(counterKey, nextCount)
|
||||
if (active.trigger.occurrence === "always") return true
|
||||
if (active.trigger.occurrence === "once") return nextCount === 1
|
||||
return nextCount === active.trigger.requestNumber
|
||||
}
|
||||
|
||||
prepareOperation(namespace: string, tool: string, idempotencyKey: string, argumentsValue: unknown): PrepareOperationResult {
|
||||
const namespaceHash = sha256(namespace)
|
||||
const idempotencyKeyHash = sha256(idempotencyKey)
|
||||
const argumentsHash = sha256(canonicalJson(argumentsValue))
|
||||
const existing = [...this.operations.values()].find(
|
||||
(operation) => operation.namespaceHash === namespaceHash && operation.idempotencyKeyHash === idempotencyKeyHash,
|
||||
)
|
||||
if (existing) {
|
||||
const operation = this.operationSummary(existing)
|
||||
if (existing.tool !== tool || existing.argumentsHash !== argumentsHash) return { kind: "conflict", operation }
|
||||
if (existing.state !== "responded") return { kind: "reconcile", operation }
|
||||
return { kind: "duplicate", operation }
|
||||
}
|
||||
|
||||
this.maintainBounds()
|
||||
if (this.operations.size >= maximumOperationCount) {
|
||||
this.trimRespondedOperations(maximumOperationCount - 1)
|
||||
if (this.operations.size >= maximumOperationCount) return { kind: "capacity" }
|
||||
}
|
||||
|
||||
const operation: MutableOperation = {
|
||||
operationId: this.issueOpaque("operation"),
|
||||
idempotencyKeyHash,
|
||||
namespaceHash,
|
||||
tool,
|
||||
argumentsHash,
|
||||
state: "prepared",
|
||||
resultReference: null,
|
||||
createdAt: this.environment.now(),
|
||||
}
|
||||
this.operations.set(operation.operationId, operation)
|
||||
this.maintainBounds()
|
||||
return { kind: "prepared", operation: this.operationSummary(operation) }
|
||||
}
|
||||
|
||||
transitionOperation(
|
||||
operationId: string,
|
||||
state: MutableOperation["state"],
|
||||
resultReference: string | null,
|
||||
): MutationOperationSummary {
|
||||
const operation = this.operations.get(operationId)
|
||||
if (!operation) throw new Error(`Unknown operation '${operationId}'`)
|
||||
operation.state = state
|
||||
operation.resultReference = resultReference
|
||||
return this.operationSummary(operation)
|
||||
}
|
||||
|
||||
snapshot(clientSecretConfigured: boolean): RuntimeSnapshot {
|
||||
this.maintainBounds()
|
||||
const baseUrl = this.runtimeBaseUrl
|
||||
return deepFreeze({
|
||||
status: this.runtimeStatus,
|
||||
instanceId: this.instanceId,
|
||||
scenario: this.currentScenario,
|
||||
profile: this.currentProfile,
|
||||
baseUrl,
|
||||
mcpUrl: baseUrl ? new URL(this.currentProfile.endpointPath, baseUrl).href : null,
|
||||
oauth: {
|
||||
authorizationServerUrl: baseUrl,
|
||||
protectedResourceMetadataUrl: baseUrl ? new URL(`/.well-known/oauth-protected-resource${this.currentProfile.endpointPath}`, baseUrl).href : null,
|
||||
registration: this.currentScenario.oauth.registration,
|
||||
clientId: this.currentScenario.oauth.clientId,
|
||||
clientSecretConfigured,
|
||||
},
|
||||
counts: {
|
||||
events: this.traceEvents.length,
|
||||
sessions: this.sessions.size,
|
||||
clients: this.clients.size,
|
||||
tokens: this.tokens.size + this.refreshTokens.size,
|
||||
operations: this.operations.size,
|
||||
},
|
||||
operations: [...this.operations.values()].map((operation) => this.operationSummary(operation)),
|
||||
})
|
||||
}
|
||||
|
||||
private operationSummary(operation: MutableOperation): MutationOperationSummary {
|
||||
return {
|
||||
operationId: operation.operationId,
|
||||
idempotencyKeyHash: operation.idempotencyKeyHash,
|
||||
tool: operation.tool,
|
||||
argumentsHash: operation.argumentsHash,
|
||||
state: operation.state,
|
||||
resultReference: operation.resultReference,
|
||||
}
|
||||
}
|
||||
|
||||
private trimOldest<Key, Value>(map: Map<Key, Value>, maximum: number): void {
|
||||
while (map.size > maximum) {
|
||||
const oldestKey = map.keys().next().value
|
||||
if (oldestKey === undefined) return
|
||||
map.delete(oldestKey)
|
||||
}
|
||||
}
|
||||
|
||||
private trimRespondedOperations(maximum: number): void {
|
||||
if (this.operations.size <= maximum) return
|
||||
for (const [operationId, operation] of this.operations) {
|
||||
if (operation.state === "responded") this.operations.delete(operationId)
|
||||
if (this.operations.size <= maximum) return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
import { randomBytes, randomUUID } from "node:crypto"
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"
|
||||
import type { Socket } from "node:net"
|
||||
import { ZodError } from "zod"
|
||||
import {
|
||||
enterpriseMcpMockSecretsSchema,
|
||||
scenarioCredentialContinuitySchema,
|
||||
ScenarioCredentialContinuityError,
|
||||
ScenarioRevisionConflictError,
|
||||
} from "../contracts/runtime.js"
|
||||
import type {
|
||||
CreateEnterpriseMcpMockServerOptions,
|
||||
EnterpriseMcpMockServer,
|
||||
RuntimeSnapshot,
|
||||
SafeTraceEvent,
|
||||
EnterpriseMcpMockEnvironment,
|
||||
UpdateScenarioOptions,
|
||||
} from "../contracts/runtime.js"
|
||||
import { scenarioSchema, type EnterpriseMcpScenario } from "../contracts/scenario.js"
|
||||
import { getProviderProfile } from "../profiles/profiles.js"
|
||||
import { getFaultDefinition } from "../faults/catalog.js"
|
||||
import { InstanceState } from "./instance-state.js"
|
||||
import { handleOAuthRequest } from "../protocol/oauth-handler.js"
|
||||
import { handleMcpRequest } from "../protocol/mcp-handler.js"
|
||||
import { HttpInputError, requestUrl, sendJson } from "../protocol/http-utils.js"
|
||||
|
||||
const defaultHost = "127.0.0.1"
|
||||
const shutdownGraceMs = 500
|
||||
|
||||
function sameExactStrings(left: readonly string[], right: readonly string[]): boolean {
|
||||
return left.length === right.length && left.every((value, index) => value === right[index])
|
||||
}
|
||||
|
||||
function validateHost(host: string): void {
|
||||
if (host !== "127.0.0.1" && host !== "::1") {
|
||||
throw new Error("Enterprise MCP mock servers bind to loopback only")
|
||||
}
|
||||
}
|
||||
|
||||
function listen(server: Server, port: number, host: string): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (error: Error): void => {
|
||||
server.off("listening", onListening)
|
||||
reject(error)
|
||||
}
|
||||
const onListening = (): void => {
|
||||
server.off("error", onError)
|
||||
const address = server.address()
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Mock server did not expose a TCP address"))
|
||||
return
|
||||
}
|
||||
resolve(address.port)
|
||||
}
|
||||
server.once("error", onError)
|
||||
server.once("listening", onListening)
|
||||
server.listen(port, host)
|
||||
})
|
||||
}
|
||||
|
||||
function close(server: Server): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) reject(error)
|
||||
else resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
class EnterpriseMcpMockServerRuntime implements EnterpriseMcpMockServer {
|
||||
private readonly host: string
|
||||
private readonly configuredPort: number
|
||||
private readonly secrets: ReturnType<typeof enterpriseMcpMockSecretsSchema.parse>
|
||||
private state: InstanceState
|
||||
private server: Server | null = null
|
||||
private sockets = new Set<Socket>()
|
||||
private activeRequestCount = 0
|
||||
private resolvedBaseUrl: string | null = null
|
||||
private lifecycleTail: Promise<void> = Promise.resolve()
|
||||
private listenAttempt = 0
|
||||
private readonly environment: EnterpriseMcpMockEnvironment
|
||||
|
||||
constructor(options: CreateEnterpriseMcpMockServerOptions) {
|
||||
this.host = options.host ?? defaultHost
|
||||
this.configuredPort = options.port ?? 0
|
||||
validateHost(this.host)
|
||||
if (!Number.isInteger(this.configuredPort) || this.configuredPort < 0 || this.configuredPort > 65_535) {
|
||||
throw new Error("Mock server port must be an integer from 0 through 65535")
|
||||
}
|
||||
const scenario = scenarioSchema.parse(options.scenario)
|
||||
this.secrets = enterpriseMcpMockSecretsSchema.parse(options.secrets)
|
||||
const profile = getProviderProfile(scenario.profileId)
|
||||
if (
|
||||
scenario.oauth.registration === "manual" &&
|
||||
profile.oauth.defaultClientAuthenticationMethod === "client_secret_post" &&
|
||||
this.secrets.oauthClientSecret.length < 12
|
||||
) {
|
||||
throw new Error(`Profile '${profile.id}' requires an OAuth client secret with at least 12 characters`)
|
||||
}
|
||||
this.environment =
|
||||
options.environment ??
|
||||
{
|
||||
now: () => Date.now(),
|
||||
randomId: () => randomUUID(),
|
||||
opaqueValue: (prefix) => `${prefix}-${randomBytes(24).toString("base64url")}`,
|
||||
}
|
||||
this.state = this.createState(scenario)
|
||||
}
|
||||
|
||||
get baseUrl(): string {
|
||||
if (!this.resolvedBaseUrl) throw new Error("Enterprise MCP mock server has not started")
|
||||
return this.resolvedBaseUrl
|
||||
}
|
||||
|
||||
get mcpUrl(): string {
|
||||
return new URL(this.state.profile.endpointPath, this.baseUrl).href
|
||||
}
|
||||
|
||||
async start(): Promise<RuntimeSnapshot> {
|
||||
return this.serializeLifecycle(() => this.startUnsafe())
|
||||
}
|
||||
|
||||
async stop(): Promise<RuntimeSnapshot> {
|
||||
return this.serializeLifecycle(async () => {
|
||||
await this.stopListener()
|
||||
this.state.clearConnectionState()
|
||||
this.resolvedBaseUrl = null
|
||||
this.state.setRuntime("stopped", null)
|
||||
return this.snapshot()
|
||||
})
|
||||
}
|
||||
|
||||
async reset(): Promise<RuntimeSnapshot> {
|
||||
return this.serializeLifecycle(async () => {
|
||||
const wasRunning = this.server !== null
|
||||
await this.stopListener()
|
||||
this.state.clearEphemeralState()
|
||||
this.state.clearEvents()
|
||||
this.resolvedBaseUrl = null
|
||||
this.state.setRuntime(wasRunning ? "idle" : "stopped", null)
|
||||
return wasRunning ? this.startUnsafe() : this.snapshot()
|
||||
})
|
||||
}
|
||||
|
||||
async updateScenario(
|
||||
nextValue: EnterpriseMcpScenario,
|
||||
expectedRevision: number,
|
||||
options: UpdateScenarioOptions = {},
|
||||
): Promise<RuntimeSnapshot> {
|
||||
return this.serializeLifecycle(async () => {
|
||||
const currentRevision = this.state.scenario.revision
|
||||
if (currentRevision !== expectedRevision) throw new ScenarioRevisionConflictError(expectedRevision, currentRevision)
|
||||
const next = scenarioSchema.parse(nextValue)
|
||||
if (next.revision !== expectedRevision + 1) {
|
||||
throw new Error(`Next scenario revision must be ${expectedRevision + 1}`)
|
||||
}
|
||||
const parsedContinuity = scenarioCredentialContinuitySchema.safeParse(options.credentialContinuity ?? "reset")
|
||||
if (!parsedContinuity.success) {
|
||||
throw new ScenarioCredentialContinuityError("unsupported_mode", "Unsupported scenario credential-continuity mode.")
|
||||
}
|
||||
const credentialContinuity = parsedContinuity.data
|
||||
if (credentialContinuity === "preserve-compatible-oauth") this.assertCompatibleOAuthContinuity(next)
|
||||
const wasRunning = this.server !== null
|
||||
const previousState = this.state
|
||||
const previousBaseUrl = this.resolvedBaseUrl
|
||||
await this.stopListener()
|
||||
this.resolvedBaseUrl = null
|
||||
const nextState = this.createState(next, previousState.instanceId)
|
||||
if (credentialContinuity === "preserve-compatible-oauth") {
|
||||
nextState.inheritEstablishedOAuthAuthority(previousState)
|
||||
}
|
||||
this.state = nextState
|
||||
nextState.setRuntime(wasRunning ? "idle" : "stopped", null)
|
||||
this.state.emit({
|
||||
correlationId: this.environment.randomId(),
|
||||
scenario: next,
|
||||
phase: "CONFIGURATION",
|
||||
direction: "internal",
|
||||
kind: "lifecycle",
|
||||
outcome: "completed",
|
||||
summary: "Activated a new immutable mock scenario revision",
|
||||
details: {
|
||||
revision: next.revision,
|
||||
profileId: next.profileId,
|
||||
faultId: next.activeFault?.id ?? null,
|
||||
credentialContinuity,
|
||||
},
|
||||
})
|
||||
if (!wasRunning) return this.snapshot()
|
||||
try {
|
||||
const activated = await this.startUnsafe()
|
||||
if (credentialContinuity === "preserve-compatible-oauth" && activated.baseUrl !== previousBaseUrl) {
|
||||
throw new ScenarioCredentialContinuityError(
|
||||
"incompatible_oauth_authority",
|
||||
"The restarted data plane did not retain its exact OAuth resource URL.",
|
||||
)
|
||||
}
|
||||
return activated
|
||||
} catch (activationError) {
|
||||
try {
|
||||
await this.stopListener()
|
||||
} catch {
|
||||
// The rollback attempt below is the authoritative recovery result.
|
||||
}
|
||||
this.state = previousState
|
||||
previousState.setRuntime("idle", null)
|
||||
try {
|
||||
await this.startUnsafe()
|
||||
} catch (rollbackError) {
|
||||
previousState.setRuntime("stopped", null)
|
||||
throw new AggregateError(
|
||||
[activationError, rollbackError],
|
||||
"Scenario activation failed and the prior listener could not be restored",
|
||||
)
|
||||
}
|
||||
throw activationError
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
snapshot(): RuntimeSnapshot {
|
||||
return this.state.snapshot(
|
||||
this.state.scenario.oauth.registration === "manual" &&
|
||||
this.state.profile.oauth.defaultClientAuthenticationMethod === "client_secret_post" &&
|
||||
this.secrets.oauthClientSecret.length > 0,
|
||||
)
|
||||
}
|
||||
|
||||
events(): readonly SafeTraceEvent[] {
|
||||
return this.state.events()
|
||||
}
|
||||
|
||||
private async startUnsafe(): Promise<RuntimeSnapshot> {
|
||||
if (this.server) return this.snapshot()
|
||||
this.seedManualClient()
|
||||
const server = createServer((request, response) => {
|
||||
// The development server can be restarted in place when a fault scenario
|
||||
// changes. Make that boundary explicit to Node and Bun clients instead
|
||||
// of leaving a reusable socket pointed at a retired listener generation.
|
||||
response.setHeader("connection", "close")
|
||||
this.activeRequestCount += 1
|
||||
let finalized = false
|
||||
const finalize = (): void => {
|
||||
if (finalized) return
|
||||
finalized = true
|
||||
this.activeRequestCount = Math.max(0, this.activeRequestCount - 1)
|
||||
}
|
||||
response.once("finish", finalize)
|
||||
response.once("close", finalize)
|
||||
void this.route(request, response)
|
||||
})
|
||||
server.on("connection", (socket) => {
|
||||
this.sockets.add(socket)
|
||||
socket.once("close", () => this.sockets.delete(socket))
|
||||
})
|
||||
this.server = server
|
||||
try {
|
||||
this.listenAttempt += 1
|
||||
await this.environment.beforeListen?.(this.listenAttempt)
|
||||
const port = await listen(server, this.configuredPort, this.host)
|
||||
const formattedHost = this.host === "::1" ? "[::1]" : this.host
|
||||
this.resolvedBaseUrl = `http://${formattedHost}:${port}`
|
||||
this.state.setRuntime("running", this.resolvedBaseUrl)
|
||||
this.state.emit({
|
||||
correlationId: this.environment.randomId(),
|
||||
scenario: this.state.scenario,
|
||||
phase: "CONFIGURATION",
|
||||
direction: "internal",
|
||||
kind: "lifecycle",
|
||||
outcome: "completed",
|
||||
summary: "Started an isolated enterprise MCP mock data plane",
|
||||
details: { host: this.host, port, profileId: this.state.profile.id },
|
||||
})
|
||||
return this.snapshot()
|
||||
} catch (error) {
|
||||
this.server = null
|
||||
this.resolvedBaseUrl = null
|
||||
this.state.setRuntime("stopped", null)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private createState(scenario: EnterpriseMcpScenario, instanceId?: string): InstanceState {
|
||||
const knownSecrets = [this.secrets.oauthClientSecret]
|
||||
return new InstanceState(scenario, getProviderProfile(scenario.profileId), knownSecrets, this.environment, instanceId)
|
||||
}
|
||||
|
||||
private assertCompatibleOAuthContinuity(next: EnterpriseMcpScenario): void {
|
||||
if (this.configuredPort === 0) {
|
||||
throw new ScenarioCredentialContinuityError(
|
||||
"fixed_port_required",
|
||||
"Preserving OAuth authority requires a fixed mock-server port so the protected resource URL cannot change.",
|
||||
)
|
||||
}
|
||||
const current = this.state.scenario
|
||||
const currentProfile = this.state.profile
|
||||
const nextProfile = getProviderProfile(next.profileId)
|
||||
const formattedHost = this.host === "::1" ? "[::1]" : this.host
|
||||
const baseUrl = `http://${formattedHost}:${this.configuredPort}`
|
||||
const currentEndpoint = new URL(currentProfile.endpointPath, baseUrl).href
|
||||
const nextEndpoint = new URL(nextProfile.endpointPath, baseUrl).href
|
||||
const compatible =
|
||||
current.profileId === next.profileId &&
|
||||
current.profileFixtureVersion === next.profileFixtureVersion &&
|
||||
currentProfile.endpointPath === nextProfile.endpointPath &&
|
||||
currentEndpoint === nextEndpoint &&
|
||||
current.oauth.registration === next.oauth.registration &&
|
||||
current.oauth.clientId === next.oauth.clientId &&
|
||||
sameExactStrings(current.oauth.redirectUris, next.oauth.redirectUris) &&
|
||||
sameExactStrings(current.oauth.authorizationScopes, next.oauth.authorizationScopes) &&
|
||||
sameExactStrings(current.oauth.requiredResourceScopes, next.oauth.requiredResourceScopes)
|
||||
if (!compatible) {
|
||||
throw new ScenarioCredentialContinuityError(
|
||||
"incompatible_oauth_authority",
|
||||
"Cannot preserve OAuth authority because the provider, endpoint, resource, client registration, redirects, or scopes changed.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private seedManualClient(): void {
|
||||
const { scenario, profile } = this.state
|
||||
if (scenario.oauth.registration !== "manual" || this.state.clients.has(scenario.oauth.clientId)) return
|
||||
const tokenEndpointAuthMethod = profile.oauth.defaultClientAuthenticationMethod
|
||||
this.state.putClient({
|
||||
clientId: scenario.oauth.clientId,
|
||||
clientSecret: tokenEndpointAuthMethod === "client_secret_post" ? this.secrets.oauthClientSecret : "",
|
||||
redirectUris: scenario.oauth.redirectUris,
|
||||
tokenEndpointAuthMethod,
|
||||
createdAt: this.environment.now(),
|
||||
expiresAt: null,
|
||||
})
|
||||
}
|
||||
|
||||
private async route(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
||||
const scenario = this.state.scenario
|
||||
const profile = this.state.profile
|
||||
const correlationId = this.environment.randomId()
|
||||
this.state.maintainBounds()
|
||||
try {
|
||||
const baseUrl = this.baseUrl
|
||||
const url = requestUrl(request, baseUrl)
|
||||
if (request.method === "GET" && url.pathname === "/health") {
|
||||
sendJson(response, 200, {
|
||||
status: "ok",
|
||||
instanceId: this.state.instanceId,
|
||||
profileId: profile.id,
|
||||
scenarioRevision: scenario.revision,
|
||||
mcpUrl: new URL(profile.endpointPath, baseUrl).href,
|
||||
})
|
||||
return
|
||||
}
|
||||
const activeFault = scenario.activeFault ? getFaultDefinition(scenario.activeFault.id) : undefined
|
||||
if (
|
||||
await handleOAuthRequest({ request, response, url, baseUrl, correlationId, scenario, profile, state: this.state, activeFault })
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (url.pathname === profile.endpointPath) {
|
||||
await handleMcpRequest({ request, response, baseUrl, correlationId, scenario, profile, state: this.state, activeFault })
|
||||
return
|
||||
}
|
||||
sendJson(response, 404, { error: "not_found" })
|
||||
} catch (error) {
|
||||
if (response.headersSent || response.destroyed) return
|
||||
if (error instanceof HttpInputError) {
|
||||
sendJson(response, error.status, { error: "invalid_http_input", message: error.message })
|
||||
return
|
||||
}
|
||||
if (error instanceof ZodError) {
|
||||
sendJson(response, 400, { error: "invalid_request", issues: error.issues.map((issue) => issue.message) })
|
||||
return
|
||||
}
|
||||
this.state.emit({
|
||||
correlationId,
|
||||
scenario,
|
||||
phase: "HTTP_ROUTING",
|
||||
direction: "internal",
|
||||
kind: "lifecycle",
|
||||
outcome: "failed",
|
||||
summary: "The mock server rejected an unexpected internal error safely",
|
||||
})
|
||||
sendJson(response, 500, { error: "mock_internal_error", diagnosticId: correlationId })
|
||||
}
|
||||
}
|
||||
|
||||
private async stopListener(): Promise<void> {
|
||||
const server = this.server
|
||||
if (!server) return
|
||||
this.server = null
|
||||
let closedGracefully = false
|
||||
const closing = close(server).then(() => {
|
||||
closedGracefully = true
|
||||
})
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined
|
||||
const deadline = new Promise<void>((resolve) => {
|
||||
timeout = setTimeout(resolve, shutdownGraceMs)
|
||||
timeout.unref()
|
||||
})
|
||||
await Promise.race([closing, deadline])
|
||||
if (timeout) clearTimeout(timeout)
|
||||
if (!closedGracefully && (this.activeRequestCount > 0 || this.sockets.size > 0)) {
|
||||
for (const socket of this.sockets) socket.destroy()
|
||||
}
|
||||
await closing
|
||||
// Let in-process HTTP clients observe the listener's FIN before a scenario
|
||||
// restart reuses the same fixed OAuth resource port. This keeps normal
|
||||
// keep-alive behavior while preventing one stale pooled request.
|
||||
await new Promise<void>((resolve) => setImmediate(resolve))
|
||||
this.sockets.clear()
|
||||
this.activeRequestCount = 0
|
||||
this.resolvedBaseUrl = null
|
||||
}
|
||||
|
||||
private serializeLifecycle<Output>(operation: () => Promise<Output>): Promise<Output> {
|
||||
const result = this.lifecycleTail.then(operation, operation)
|
||||
this.lifecycleTail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
export function createEnterpriseMcpMockServer(options: CreateEnterpriseMcpMockServerOptions): EnterpriseMcpMockServer {
|
||||
return new EnterpriseMcpMockServerRuntime(options)
|
||||
}
|
||||
@@ -0,0 +1,952 @@
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto"
|
||||
import { z } from "zod"
|
||||
import type { EnterpriseMcpScenario } from "../contracts/scenario.js"
|
||||
import type { HandshakePhase } from "../contracts/phases.js"
|
||||
import { scenarioSchema } from "../contracts/scenario.js"
|
||||
import { getProviderProfile } from "../profiles/profiles.js"
|
||||
import { getFaultDefinition } from "../faults/catalog.js"
|
||||
import { toolInputSchemaSchema, type MockTool, type ToolInputSchema, type ToolSchemaNode } from "../contracts/tool.js"
|
||||
|
||||
export interface ProbeCredentials {
|
||||
readonly clientSecret: string
|
||||
}
|
||||
|
||||
export interface ProbeEnterpriseMcpMockServerOptions {
|
||||
readonly baseUrl: string
|
||||
readonly scenario: EnterpriseMcpScenario
|
||||
readonly credentials?: ProbeCredentials
|
||||
readonly mode?: ProbeMode
|
||||
readonly timeoutMs?: number
|
||||
readonly callTool?: {
|
||||
readonly name: string
|
||||
readonly arguments: Readonly<Record<string, unknown>>
|
||||
}
|
||||
}
|
||||
|
||||
export type ProbeMode = "connection-readiness" | "fixture-conformance" | "safe-read"
|
||||
|
||||
export interface ProbePhaseResult {
|
||||
readonly phase: HandshakePhase
|
||||
readonly status: "passed" | "failed" | "skipped"
|
||||
readonly elapsedMs: number
|
||||
readonly summary: string
|
||||
}
|
||||
|
||||
export interface ProbeError {
|
||||
readonly phase: HandshakePhase
|
||||
readonly category: string
|
||||
readonly messageSafe: string
|
||||
}
|
||||
|
||||
export interface ProbeResult {
|
||||
readonly ok: boolean
|
||||
readonly diagnosticId: string
|
||||
readonly mode: ProbeMode
|
||||
readonly expected: EnterpriseMcpScenario["expected"]
|
||||
readonly observed: {
|
||||
readonly outcome: "success" | "failure"
|
||||
readonly firstFailedPhase: HandshakePhase | null
|
||||
readonly category: string | null
|
||||
}
|
||||
readonly phases: readonly ProbePhaseResult[]
|
||||
readonly negotiatedProtocolVersion: string | null
|
||||
readonly toolCount: number
|
||||
readonly error: ProbeError | null
|
||||
}
|
||||
|
||||
const protectedResourceMetadataSchema = z.object({
|
||||
resource: z.url(),
|
||||
authorization_servers: z.array(z.url()).min(1),
|
||||
scopes_supported: z.array(z.string()).min(1),
|
||||
})
|
||||
|
||||
const authorizationServerMetadataSchema = z.object({
|
||||
issuer: z.url(),
|
||||
authorization_endpoint: z.url(),
|
||||
token_endpoint: z.url(),
|
||||
registration_endpoint: z.url().optional(),
|
||||
revocation_endpoint: z.url().optional(),
|
||||
code_challenge_methods_supported: z.array(z.string()).min(1),
|
||||
})
|
||||
|
||||
const registrationResponseSchema = z.object({
|
||||
client_id: z.string().min(1),
|
||||
client_secret: z.string().optional(),
|
||||
token_endpoint_auth_method: z.enum(["none", "client_secret_post"]),
|
||||
})
|
||||
|
||||
const tokenResponseSchema = z.object({
|
||||
access_token: z.string().min(1),
|
||||
refresh_token: z.string().min(1),
|
||||
token_type: z.enum(["Bearer", "user"]),
|
||||
ok: z.literal(true).optional(),
|
||||
})
|
||||
|
||||
const rpcEnvelopeSchema = 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(),
|
||||
})
|
||||
|
||||
const initializeResultSchema = z.object({
|
||||
protocolVersion: z.string(),
|
||||
capabilities: z.record(z.string(), z.unknown()),
|
||||
serverInfo: z.object({ name: z.string(), version: z.string() }),
|
||||
})
|
||||
|
||||
const toolsListResultSchema = z.object({
|
||||
tools: z.array(
|
||||
z.object({
|
||||
name: z.string().min(1),
|
||||
title: z.string().optional(),
|
||||
description: z.string(),
|
||||
inputSchema: z.unknown(),
|
||||
}),
|
||||
),
|
||||
nextCursor: z.string().optional(),
|
||||
})
|
||||
|
||||
const maximumProbeResponseBytes = 1024 * 1024
|
||||
const responseDeadlines = new WeakMap<Response, number>()
|
||||
|
||||
class ProbeFailure extends Error {
|
||||
readonly phase: HandshakePhase
|
||||
readonly category: string
|
||||
|
||||
constructor(phase: HandshakePhase, category: string, message: string) {
|
||||
super(message)
|
||||
this.name = "ProbeFailure"
|
||||
this.phase = phase
|
||||
this.category = category
|
||||
}
|
||||
}
|
||||
|
||||
function assertLocalProbeBase(baseUrl: URL): void {
|
||||
if (
|
||||
baseUrl.protocol !== "http:" ||
|
||||
(baseUrl.hostname !== "127.0.0.1" && baseUrl.hostname !== "[::1]" && baseUrl.hostname !== "::1") ||
|
||||
baseUrl.username ||
|
||||
baseUrl.password ||
|
||||
baseUrl.hash
|
||||
) {
|
||||
throw new ProbeFailure("CONFIGURATION", "configuration", "Mock probes are restricted to literal loopback HTTP origins")
|
||||
}
|
||||
}
|
||||
|
||||
function assertPinnedOrigin(urlValue: string | URL, baseUrl: URL, phase: HandshakePhase): URL {
|
||||
if (hasTrailingDotHost(urlValue)) {
|
||||
throw new ProbeFailure(phase, "oauth_trailing_dot_url", "Discovered endpoint used a stray trailing-dot URL")
|
||||
}
|
||||
const url = new URL(urlValue)
|
||||
if (url.origin !== baseUrl.origin || url.username || url.password || url.hash) {
|
||||
throw new ProbeFailure(phase, defaultCategory(phase), "Discovered endpoint escaped the expected local mock origin")
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
function hasTrailingDotHost(urlValue: string | URL): boolean {
|
||||
const text = typeof urlValue === "string" ? urlValue : urlValue.href
|
||||
const withoutScheme = text.split("://", 2)[1]
|
||||
if (!withoutScheme) return false
|
||||
const authority = withoutScheme.split(/[/?#]/u, 1)[0] ?? ""
|
||||
const hostPort = authority.includes("@") ? authority.slice(authority.lastIndexOf("@") + 1) : authority
|
||||
if (hostPort.startsWith("[")) return false
|
||||
const host = hostPort.split(":", 1)[0] ?? ""
|
||||
return host.endsWith(".")
|
||||
}
|
||||
|
||||
async function fetchStep(
|
||||
input: string | URL,
|
||||
init: RequestInit | undefined,
|
||||
phase: HandshakePhase,
|
||||
overallDeadline: number,
|
||||
): Promise<Response> {
|
||||
const remainingMs = overallDeadline - Date.now()
|
||||
if (remainingMs <= 0) throw new ProbeFailure(phase, defaultCategory(phase), `Probe exceeded its overall deadline at ${phase}`)
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), Math.min(5_000, remainingMs))
|
||||
try {
|
||||
const response = await fetch(input, { ...init, redirect: init?.redirect ?? "manual", signal: controller.signal })
|
||||
responseDeadlines.set(response, Math.min(overallDeadline, Date.now() + 5_000))
|
||||
return response
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) throw new ProbeFailure(phase, defaultCategory(phase), `Probe step ${phase} timed out`)
|
||||
throw new ProbeFailure(
|
||||
"NETWORK_TCP",
|
||||
"network_tcp",
|
||||
`The loopback MCP endpoint closed or refused the TCP connection before ${phase} returned an HTTP response`,
|
||||
)
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
async function boundedResponseText(response: Response, phase: HandshakePhase, category: string): Promise<string> {
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) return ""
|
||||
const deadline = responseDeadlines.get(response) ?? Date.now() + 5_000
|
||||
const decoder = new TextDecoder()
|
||||
let byteCount = 0
|
||||
let text = ""
|
||||
try {
|
||||
for (;;) {
|
||||
const remainingMs = deadline - Date.now()
|
||||
if (remainingMs <= 0) throw new ProbeFailure(phase, category, `Response body timed out at ${phase}`)
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined
|
||||
let result: ReadableStreamReadResult<Uint8Array>
|
||||
try {
|
||||
result = await Promise.race([
|
||||
reader.read(),
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => reject(new ProbeFailure(phase, category, `Response body timed out at ${phase}`)), remainingMs)
|
||||
timeout.unref()
|
||||
}),
|
||||
])
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout)
|
||||
}
|
||||
if (result.done) break
|
||||
byteCount += result.value.byteLength
|
||||
if (byteCount > maximumProbeResponseBytes) {
|
||||
throw new ProbeFailure(phase, category, `Response body exceeded the ${maximumProbeResponseBytes}-byte probe limit`)
|
||||
}
|
||||
text += decoder.decode(result.value, { stream: true })
|
||||
}
|
||||
return text + decoder.decode()
|
||||
} catch (error) {
|
||||
await reader.cancel().catch(() => undefined)
|
||||
throw error
|
||||
} finally {
|
||||
reader.releaseLock()
|
||||
}
|
||||
}
|
||||
|
||||
async function discardResponseBody(response: Response, phase: HandshakePhase, category = defaultCategory(phase)): Promise<void> {
|
||||
await boundedResponseText(response, phase, category)
|
||||
}
|
||||
|
||||
interface MutableProbeState {
|
||||
negotiatedProtocolVersion: string | null
|
||||
toolCount: number
|
||||
}
|
||||
|
||||
async function parseJson(response: Response, phase: HandshakePhase, category: string): Promise<unknown> {
|
||||
const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
|
||||
const text = await boundedResponseText(response, phase, category)
|
||||
if (contentType !== "application/json") throw new ProbeFailure(phase, category, `Expected JSON but received '${contentType || "no content type"}'`)
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(text)
|
||||
return parsed
|
||||
} catch {
|
||||
throw new ProbeFailure(phase, category, "Response body was not valid JSON")
|
||||
}
|
||||
}
|
||||
|
||||
async function parseRpc(response: Response, phase: HandshakePhase): Promise<z.infer<typeof rpcEnvelopeSchema>> {
|
||||
const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
|
||||
let value: unknown
|
||||
if (contentType === "text/event-stream") {
|
||||
const text = await boundedResponseText(response, phase, "mcp_transport")
|
||||
const dataLine = text
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith("data: "))
|
||||
if (!dataLine) throw new ProbeFailure("MCP_TRANSPORT", "mcp_transport", "SSE response did not contain a complete data frame")
|
||||
try {
|
||||
value = JSON.parse(dataLine.slice("data: ".length))
|
||||
} catch {
|
||||
throw new ProbeFailure("MCP_TRANSPORT", "mcp_transport", "SSE data frame did not contain valid JSON")
|
||||
}
|
||||
} else if (contentType === "application/json") {
|
||||
value = await parseJson(response, phase, "mcp_transport")
|
||||
} else {
|
||||
throw new ProbeFailure("MCP_TRANSPORT", "mcp_transport", `Unexpected MCP response content type '${contentType || "none"}'`)
|
||||
}
|
||||
const envelope = rpcEnvelopeSchema.safeParse(value)
|
||||
if (!envelope.success) throw new ProbeFailure(phase, "mcp_transport", "Response was not a valid JSON-RPC envelope")
|
||||
return envelope.data
|
||||
}
|
||||
|
||||
function defaultCategory(phase: HandshakePhase): string {
|
||||
if (phase === "AUTH_RESOURCE_DISCOVERY") return "oauth_discovery_resource"
|
||||
if (phase === "AUTH_ISSUER_DISCOVERY") return "oauth_discovery_issuer"
|
||||
if (phase === "AUTH_CLIENT_REGISTRATION") return "oauth_client_registration"
|
||||
if (phase === "AUTH_USER_OR_WORKLOAD") return "oauth_authorization"
|
||||
if (phase === "AUTH_TOKEN_ACQUISITION") return "oauth_token"
|
||||
if (phase === "CONTINUITY_REFRESH") return "oauth_credential_expired"
|
||||
if (phase === "AUTH_RESOURCE_VALIDATION") return "resource_token_validation"
|
||||
if (phase === "MCP_VERSION") return "mcp_version"
|
||||
if (phase === "MCP_INITIALIZE") return "mcp_initialize"
|
||||
if (phase === "MCP_INITIALIZED") return "mcp_lifecycle"
|
||||
if (phase === "MCP_TOOL_DISCOVERY") return "mcp_tools_discovery"
|
||||
if (phase === "CONTINUITY_SESSION") return "mcp_session"
|
||||
if (phase === "PROVIDER_AUTHORIZATION") return "provider_authorization_denied"
|
||||
if (phase === "PROVIDER_EXECUTION") return "provider_api"
|
||||
return "mcp_transport"
|
||||
}
|
||||
|
||||
function redactProbeMessage(message: string, secretValues: readonly string[]): string {
|
||||
let safe = message
|
||||
for (const secret of secretValues) {
|
||||
if (secret) safe = safe.replaceAll(secret, "[REDACTED]")
|
||||
}
|
||||
return safe
|
||||
.replace(/Bearer\s+[A-Za-z0-9._~-]+/gi, "Bearer [REDACTED]")
|
||||
.replace(/(client[_ -]?secret|authorization[_ -]?code|code[_ -]?verifier|access[_ -]?token|refresh[_ -]?token)\s*[:=]\s*[^\s,;]+/gi, "$1=[REDACTED]")
|
||||
.slice(0, 500)
|
||||
}
|
||||
|
||||
async function expectOk(response: Response, phase: HandshakePhase): Promise<Response> {
|
||||
if (response.ok) return response
|
||||
let message = `HTTP ${response.status}`
|
||||
let category = defaultCategory(phase)
|
||||
try {
|
||||
const body = await boundedResponseText(response, phase, category)
|
||||
const parsed: unknown = JSON.parse(body)
|
||||
const errorBody = z.object({ error: z.string(), error_description: z.string().optional(), message: z.string().optional() }).safeParse(parsed)
|
||||
if (errorBody.success) {
|
||||
message = errorBody.data.error_description ?? errorBody.data.message ?? errorBody.data.error
|
||||
if (errorBody.data.error === "invalid_client") category = "oauth_client_registration"
|
||||
if (errorBody.data.error === "invalid_grant") category = "oauth_token"
|
||||
if (errorBody.data.error === "dynamic_client_registration_required") category = "oauth_dynamic_registration_required"
|
||||
if (message.includes("redirect URI is not an allowed destination")) category = "oauth_redirect_uri_whitelist"
|
||||
}
|
||||
} catch {
|
||||
// Status and phase remain sufficient safe evidence.
|
||||
}
|
||||
throw new ProbeFailure(phase, category, message)
|
||||
}
|
||||
|
||||
async function safeHttpErrorMessage(response: Response, phase: HandshakePhase, category: string): Promise<string> {
|
||||
const text = await boundedResponseText(response, phase, category)
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(text)
|
||||
const errorBody = z.object({ error: z.string().optional(), error_description: z.string().optional(), message: z.string().optional() }).safeParse(parsed)
|
||||
if (errorBody.success) return errorBody.data.error_description ?? errorBody.data.message ?? errorBody.data.error ?? `HTTP ${response.status}`
|
||||
} catch {
|
||||
// The HTTP status remains sufficient safe evidence.
|
||||
}
|
||||
return text.trim() || `HTTP ${response.status}`
|
||||
}
|
||||
|
||||
function recordPassed(phases: ProbePhaseResult[], phase: HandshakePhase, startedAt: number, summary: string): void {
|
||||
phases.push({ phase, status: "passed", elapsedMs: Date.now() - startedAt, summary })
|
||||
}
|
||||
|
||||
function parseAt<Output>(
|
||||
schema: z.ZodType<Output>,
|
||||
value: unknown,
|
||||
phase: HandshakePhase,
|
||||
category: string,
|
||||
message: string,
|
||||
): Output {
|
||||
const parsed = schema.safeParse(value)
|
||||
if (!parsed.success) throw new ProbeFailure(phase, category, message)
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
function defaultArguments(schema: ToolInputSchema): Readonly<Record<string, unknown>> {
|
||||
const value: Record<string, unknown> = {}
|
||||
for (const name of schema.required) {
|
||||
const property = schema.properties[name]
|
||||
if (!property) continue
|
||||
if (name === "approved") value[name] = true
|
||||
else if (name === "idempotency_key") value[name] = "probe-idempotency-key"
|
||||
else value[name] = defaultArgumentValue(property, name)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function defaultArgumentValue(schema: ToolSchemaNode, name: string): unknown {
|
||||
if ("oneOf" in schema) return defaultArgumentValue(schema.oneOf[0] ?? { type: "null" }, name)
|
||||
if ("anyOf" in schema) return defaultArgumentValue(schema.anyOf[0] ?? { type: "null" }, name)
|
||||
if (schema.type === "string") return schema.enum?.[0] ?? (name === "number" ? "INC0000001" : "synthetic-probe-value")
|
||||
if (schema.type === "number" || schema.type === "integer") return schema.minimum ?? 1
|
||||
if (schema.type === "boolean") return true
|
||||
if (schema.type === "null") return null
|
||||
if (schema.type === "array") {
|
||||
const count = Math.max(1, schema.minItems ?? 0)
|
||||
return Array.from({ length: count }, () => defaultArgumentValue(schema.items, name))
|
||||
}
|
||||
if (schema.type !== "object") return null
|
||||
const value: Record<string, unknown> = {}
|
||||
for (const requiredName of schema.required) {
|
||||
const property = schema.properties[requiredName]
|
||||
if (property) value[requiredName] = defaultArgumentValue(property, requiredName)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function classifyProviderToolError(value: unknown): ProbeFailure {
|
||||
const parsed = z
|
||||
.object({
|
||||
error: z.object({ code: z.string(), message: z.string().optional() }),
|
||||
})
|
||||
.safeParse(value)
|
||||
if (!parsed.success) {
|
||||
return new ProbeFailure("MCP_TOOL_EXECUTION", "mcp_tool", "Provider returned an unclassified MCP tool error")
|
||||
}
|
||||
const code = parsed.data.error.code
|
||||
if (code === "PROVIDER_ACL_DENIED") {
|
||||
return new ProbeFailure("PROVIDER_AUTHORIZATION", "provider_authorization_denied", "Provider ACL denied the tool operation")
|
||||
}
|
||||
if (code === "PROVIDER_POLICY_DENIED") {
|
||||
return new ProbeFailure("PROVIDER_AUTHORIZATION", "provider_policy_denied", "Provider policy denied the tool operation")
|
||||
}
|
||||
if (code === "PROVIDER_THROTTLED") {
|
||||
return new ProbeFailure("PROVIDER_EXECUTION", "provider_throttled", "Provider throttled the tool operation")
|
||||
}
|
||||
if (code === "PROVIDER_UNAVAILABLE") {
|
||||
return new ProbeFailure("PROVIDER_EXECUTION", "provider_unavailable", "Provider was unavailable during the tool operation")
|
||||
}
|
||||
if (code === "PROVIDER_DUPLICATE_REQUEST") {
|
||||
return new ProbeFailure("PROVIDER_EXECUTION", "provider_duplicate_request", "The gateway amplified one MCP tool call into duplicate requests")
|
||||
}
|
||||
return new ProbeFailure("MCP_TOOL_EXECUTION", "mcp_tool", `Provider returned tool error '${code}'`)
|
||||
}
|
||||
|
||||
export async function probeEnterpriseMcpMockServer(options: ProbeEnterpriseMcpMockServerOptions): Promise<ProbeResult> {
|
||||
const diagnosticId = randomUUID()
|
||||
const scenario = scenarioSchema.parse(options.scenario)
|
||||
const profile = getProviderProfile(scenario.profileId)
|
||||
const activeFault = scenario.activeFault ? getFaultDefinition(scenario.activeFault.id) : undefined
|
||||
const mode = options.mode ?? "fixture-conformance"
|
||||
const baseUrl = new URL(options.baseUrl)
|
||||
assertLocalProbeBase(baseUrl)
|
||||
const mcpUrl = new URL(profile.endpointPath, baseUrl).href
|
||||
const timeoutMs = options.timeoutMs ?? 30_000
|
||||
if (!Number.isInteger(timeoutMs) || timeoutMs < 50 || timeoutMs > 120_000) {
|
||||
throw new ProbeFailure("CONFIGURATION", "configuration", "Probe timeout must be an integer from 50 through 120000 milliseconds")
|
||||
}
|
||||
const overallDeadline = Date.now() + timeoutMs
|
||||
const phases: ProbePhaseResult[] = []
|
||||
const mutable: MutableProbeState = { negotiatedProtocolVersion: null, toolCount: 0 }
|
||||
const sensitiveValues = [options.credentials?.clientSecret ?? ""]
|
||||
let sessionId = ""
|
||||
let accessToken = ""
|
||||
let refreshToken = ""
|
||||
let revocationClientId = scenario.oauth.clientId
|
||||
let revocationClientSecret = options.credentials?.clientSecret ?? ""
|
||||
let negotiatedProtocolHeader = ""
|
||||
let revocationEndpoint: URL | null = null
|
||||
const cleanup = async (requireValidDelete: boolean): Promise<void> => {
|
||||
const cleanupDeadline = Date.now() + 2_000
|
||||
if (sessionId && accessToken && negotiatedProtocolHeader) {
|
||||
try {
|
||||
const deleteResponse = await fetchStep(mcpUrl, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
authorization: `Bearer ${accessToken}`,
|
||||
origin: baseUrl.origin,
|
||||
"mcp-session-id": sessionId,
|
||||
"mcp-protocol-version": negotiatedProtocolHeader,
|
||||
},
|
||||
}, "SHUTDOWN", cleanupDeadline)
|
||||
await discardResponseBody(deleteResponse, "SHUTDOWN", "mcp_session")
|
||||
if (requireValidDelete && deleteResponse.status !== 204) {
|
||||
throw new ProbeFailure("SHUTDOWN", "mcp_session", `Session DELETE returned HTTP ${deleteResponse.status}`)
|
||||
}
|
||||
} catch (error) {
|
||||
if (requireValidDelete) throw error
|
||||
}
|
||||
}
|
||||
if (revocationEndpoint && accessToken) {
|
||||
try {
|
||||
const revocationResponse = await fetchStep(revocationEndpoint, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
token: accessToken,
|
||||
client_id: revocationClientId,
|
||||
...(revocationClientSecret ? { client_secret: revocationClientSecret } : {}),
|
||||
}),
|
||||
}, "SHUTDOWN", cleanupDeadline)
|
||||
await discardResponseBody(revocationResponse, "SHUTDOWN", "oauth_token")
|
||||
} catch {
|
||||
// Cleanup never replaces the primary diagnostic failure.
|
||||
}
|
||||
}
|
||||
if (revocationEndpoint && refreshToken) {
|
||||
try {
|
||||
const revocationResponse = await fetchStep(revocationEndpoint, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
token: refreshToken,
|
||||
client_id: revocationClientId,
|
||||
...(revocationClientSecret ? { client_secret: revocationClientSecret } : {}),
|
||||
}),
|
||||
}, "SHUTDOWN", cleanupDeadline)
|
||||
await discardResponseBody(revocationResponse, "SHUTDOWN", "oauth_token")
|
||||
} catch {
|
||||
// Cleanup never replaces the primary diagnostic failure.
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
let startedAt = Date.now()
|
||||
if (activeFault?.effect === "method-405") {
|
||||
const methodResponse = await fetchStep(mcpUrl, { method: "GET" }, "HTTP_ROUTING", overallDeadline)
|
||||
await discardResponseBody(methodResponse, "HTTP_ROUTING", "mcp_method_405")
|
||||
throw new ProbeFailure(
|
||||
"HTTP_ROUTING",
|
||||
methodResponse.status === 405 ? "mcp_method_405" : "http_failure",
|
||||
`MCP endpoint returned HTTP ${methodResponse.status} to GET`,
|
||||
)
|
||||
}
|
||||
const challengeResponse = await fetchStep(
|
||||
mcpUrl,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
accept: "application/json, text/event-stream",
|
||||
"content-type": "application/json",
|
||||
origin: baseUrl.origin,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: 0,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: scenario.protocol.version,
|
||||
capabilities: {},
|
||||
clientInfo: { name: "enterprise-mcp-probe", version: "0.1.0" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
"AUTH_RESOURCE_DISCOVERY",
|
||||
overallDeadline,
|
||||
)
|
||||
await discardResponseBody(challengeResponse, "AUTH_RESOURCE_DISCOVERY", "oauth_discovery_resource")
|
||||
if (challengeResponse.status !== 401) {
|
||||
throw new ProbeFailure("AUTH_RESOURCE_DISCOVERY", "oauth_discovery_resource", `Unauthenticated MCP probe returned HTTP ${challengeResponse.status}, not 401`)
|
||||
}
|
||||
const challengeHeader = challengeResponse.headers.get("www-authenticate") ?? ""
|
||||
const metadataMatch = /resource_metadata="([^"]+)"/.exec(challengeHeader)
|
||||
const metadataUrlValue = metadataMatch?.[1]
|
||||
if (!metadataUrlValue) {
|
||||
throw new ProbeFailure("AUTH_RESOURCE_DISCOVERY", "oauth_discovery_resource", "MCP 401 challenge did not provide resource_metadata")
|
||||
}
|
||||
const resourceMetadataUrl = assertPinnedOrigin(metadataUrlValue, baseUrl, "AUTH_RESOURCE_DISCOVERY")
|
||||
const expectedMetadataPath = `/.well-known/oauth-protected-resource${profile.endpointPath}`
|
||||
if (resourceMetadataUrl.pathname !== expectedMetadataPath) {
|
||||
throw new ProbeFailure("AUTH_RESOURCE_DISCOVERY", "oauth_discovery_resource", "MCP challenge pointed to unexpected protected-resource metadata")
|
||||
}
|
||||
const resourceResponse = await expectOk(
|
||||
await fetchStep(resourceMetadataUrl, undefined, "AUTH_RESOURCE_DISCOVERY", overallDeadline),
|
||||
"AUTH_RESOURCE_DISCOVERY",
|
||||
)
|
||||
const resourceMetadata = parseAt(
|
||||
protectedResourceMetadataSchema,
|
||||
await parseJson(resourceResponse, "AUTH_RESOURCE_DISCOVERY", "oauth_discovery_resource"),
|
||||
"AUTH_RESOURCE_DISCOVERY",
|
||||
"oauth_discovery_resource",
|
||||
"Protected-resource metadata did not match the required shape",
|
||||
)
|
||||
if (resourceMetadata.resource !== mcpUrl) {
|
||||
throw new ProbeFailure("AUTH_RESOURCE_DISCOVERY", "oauth_discovery_resource", "Protected-resource metadata did not identify this MCP endpoint")
|
||||
}
|
||||
recordPassed(phases, "AUTH_RESOURCE_DISCOVERY", startedAt, "Protected-resource metadata is coherent")
|
||||
|
||||
startedAt = Date.now()
|
||||
const authorizationServerValue = resourceMetadata.authorization_servers[0]
|
||||
if (!authorizationServerValue) {
|
||||
throw new ProbeFailure("AUTH_ISSUER_DISCOVERY", "oauth_discovery_issuer", "Protected-resource metadata had no authorization server")
|
||||
}
|
||||
const issuerMetadataResponse = await expectOk(
|
||||
await fetchStep(
|
||||
new URL("/.well-known/oauth-authorization-server", assertPinnedOrigin(authorizationServerValue, baseUrl, "AUTH_ISSUER_DISCOVERY")),
|
||||
undefined,
|
||||
"AUTH_ISSUER_DISCOVERY",
|
||||
overallDeadline,
|
||||
),
|
||||
"AUTH_ISSUER_DISCOVERY",
|
||||
)
|
||||
const issuerMetadata = parseAt(
|
||||
authorizationServerMetadataSchema,
|
||||
await parseJson(issuerMetadataResponse, "AUTH_ISSUER_DISCOVERY", "oauth_discovery_issuer"),
|
||||
"AUTH_ISSUER_DISCOVERY",
|
||||
"oauth_discovery_issuer",
|
||||
"Authorization-server metadata did not match the required shape",
|
||||
)
|
||||
if (issuerMetadata.issuer !== baseUrl.href.replace(/\/$/, "")) {
|
||||
throw new ProbeFailure("AUTH_ISSUER_DISCOVERY", "oauth_discovery_issuer", "Authorization-server metadata issuer did not match")
|
||||
}
|
||||
const authorizationEndpoint = assertPinnedOrigin(issuerMetadata.authorization_endpoint, baseUrl, "AUTH_ISSUER_DISCOVERY")
|
||||
const tokenEndpoint = assertPinnedOrigin(issuerMetadata.token_endpoint, baseUrl, "AUTH_ISSUER_DISCOVERY")
|
||||
const registrationEndpoint = issuerMetadata.registration_endpoint
|
||||
? assertPinnedOrigin(issuerMetadata.registration_endpoint, baseUrl, "AUTH_CLIENT_REGISTRATION")
|
||||
: undefined
|
||||
revocationEndpoint = issuerMetadata.revocation_endpoint
|
||||
? assertPinnedOrigin(issuerMetadata.revocation_endpoint, baseUrl, "AUTH_ISSUER_DISCOVERY")
|
||||
: null
|
||||
if (!issuerMetadata.code_challenge_methods_supported.includes("S256")) {
|
||||
throw new ProbeFailure("AUTH_ISSUER_DISCOVERY", "oauth_pkce_unsupported", "Authorization server did not advertise PKCE S256")
|
||||
}
|
||||
recordPassed(phases, "AUTH_ISSUER_DISCOVERY", startedAt, "Authorization-server metadata and PKCE S256 are usable")
|
||||
|
||||
let clientId = scenario.oauth.clientId
|
||||
let clientSecret = options.credentials?.clientSecret ?? ""
|
||||
let tokenAuthMethod: "none" | "client_secret_post" = profile.oauth.defaultClientAuthenticationMethod
|
||||
startedAt = Date.now()
|
||||
if (scenario.oauth.registration === "dynamic") {
|
||||
if (!registrationEndpoint) {
|
||||
throw new ProbeFailure("AUTH_CLIENT_REGISTRATION", "oauth_client_registration", "Authorization server did not advertise dynamic registration")
|
||||
}
|
||||
tokenAuthMethod = profile.oauth.defaultClientAuthenticationMethod
|
||||
const registrationResponse = await expectOk(
|
||||
await fetchStep(registrationEndpoint, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
redirect_uris: scenario.oauth.redirectUris,
|
||||
token_endpoint_auth_method: tokenAuthMethod,
|
||||
client_name: "OpenWork enterprise MCP probe",
|
||||
}),
|
||||
}, "AUTH_CLIENT_REGISTRATION", overallDeadline),
|
||||
"AUTH_CLIENT_REGISTRATION",
|
||||
)
|
||||
const registration = parseAt(
|
||||
registrationResponseSchema,
|
||||
await parseJson(registrationResponse, "AUTH_CLIENT_REGISTRATION", "oauth_client_registration"),
|
||||
"AUTH_CLIENT_REGISTRATION",
|
||||
"oauth_client_registration",
|
||||
"Dynamic registration response did not match the required shape",
|
||||
)
|
||||
clientId = registration.client_id
|
||||
clientSecret = registration.client_secret ?? ""
|
||||
if (clientSecret) sensitiveValues.push(clientSecret)
|
||||
tokenAuthMethod = registration.token_endpoint_auth_method
|
||||
} else if (tokenAuthMethod === "client_secret_post" && !clientSecret) {
|
||||
throw new ProbeFailure("AUTH_CLIENT_REGISTRATION", "oauth_client_registration", "Manual OAuth profile requires a client secret")
|
||||
}
|
||||
revocationClientId = clientId
|
||||
revocationClientSecret = tokenAuthMethod === "client_secret_post" ? clientSecret : ""
|
||||
recordPassed(phases, "AUTH_CLIENT_REGISTRATION", startedAt, "OAuth client identification is ready")
|
||||
|
||||
const verifier = randomBytes(32).toString("base64url")
|
||||
const pkceChallengeValue = createHash("sha256").update(verifier).digest("base64url")
|
||||
const oauthState = randomBytes(16).toString("base64url")
|
||||
sensitiveValues.push(verifier, oauthState)
|
||||
const redirectUri = scenario.oauth.redirectUris[0]
|
||||
if (!redirectUri) throw new ProbeFailure("CONFIGURATION", "configuration", "Scenario has no redirect URI")
|
||||
const authorizeUrl = new URL(authorizationEndpoint)
|
||||
authorizeUrl.searchParams.set("response_type", "code")
|
||||
authorizeUrl.searchParams.set("client_id", clientId)
|
||||
authorizeUrl.searchParams.set("redirect_uri", redirectUri)
|
||||
authorizeUrl.searchParams.set("scope", scenario.oauth.authorizationScopes.join(" "))
|
||||
authorizeUrl.searchParams.set("resource", mcpUrl)
|
||||
authorizeUrl.searchParams.set("state", oauthState)
|
||||
authorizeUrl.searchParams.set("code_challenge", pkceChallengeValue)
|
||||
authorizeUrl.searchParams.set("code_challenge_method", "S256")
|
||||
startedAt = Date.now()
|
||||
const authorizeResponse = await fetchStep(authorizeUrl, { redirect: "manual" }, "AUTH_USER_OR_WORKLOAD", overallDeadline)
|
||||
if (authorizeResponse.status !== 302) await expectOk(authorizeResponse, "AUTH_USER_OR_WORKLOAD")
|
||||
else await discardResponseBody(authorizeResponse, "AUTH_USER_OR_WORKLOAD", "oauth_authorization")
|
||||
const location = authorizeResponse.headers.get("location")
|
||||
if (!location) throw new ProbeFailure("AUTH_USER_OR_WORKLOAD", "oauth_authorization", "Authorization response had no redirect location")
|
||||
const callback = new URL(location)
|
||||
const callbackWithoutResponse = new URL(callback)
|
||||
callbackWithoutResponse.searchParams.delete("code")
|
||||
callbackWithoutResponse.searchParams.delete("state")
|
||||
if (callbackWithoutResponse.href !== redirectUri) {
|
||||
throw new ProbeFailure("AUTH_USER_OR_WORKLOAD", "oauth_authorization", "Authorization callback did not exactly match the registered redirect URI")
|
||||
}
|
||||
if (callback.searchParams.get("state") !== oauthState || !callback.searchParams.get("code")) {
|
||||
throw new ProbeFailure("AUTH_USER_OR_WORKLOAD", "oauth_authorization", "Authorization callback state or code was invalid")
|
||||
}
|
||||
sensitiveValues.push(callback.searchParams.get("code") ?? "")
|
||||
recordPassed(phases, "AUTH_USER_OR_WORKLOAD", startedAt, "Synthetic user authorization and state binding passed")
|
||||
|
||||
startedAt = Date.now()
|
||||
const tokenForm = new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
client_id: clientId,
|
||||
code: callback.searchParams.get("code") ?? "",
|
||||
redirect_uri: redirectUri,
|
||||
code_verifier: verifier,
|
||||
resource: mcpUrl,
|
||||
})
|
||||
if (tokenAuthMethod === "client_secret_post") tokenForm.set("client_secret", clientSecret)
|
||||
const tokenResponse = await expectOk(
|
||||
await fetchStep(tokenEndpoint, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: tokenForm,
|
||||
}, "AUTH_TOKEN_ACQUISITION", overallDeadline),
|
||||
"AUTH_TOKEN_ACQUISITION",
|
||||
)
|
||||
const token = parseAt(
|
||||
tokenResponseSchema,
|
||||
await parseJson(tokenResponse, "AUTH_TOKEN_ACQUISITION", "oauth_token"),
|
||||
"AUTH_TOKEN_ACQUISITION",
|
||||
"oauth_token",
|
||||
"Token response did not match the required shape",
|
||||
)
|
||||
const expectedTokenType = profile.oauth.tokenResponseStyle === "slack-user" ? "user" : "Bearer"
|
||||
if (token.token_type !== expectedTokenType || (expectedTokenType === "user" && token.ok !== true)) {
|
||||
throw new ProbeFailure("AUTH_TOKEN_ACQUISITION", "oauth_token", "Token response did not match the selected provider profile")
|
||||
}
|
||||
accessToken = token.access_token
|
||||
refreshToken = token.refresh_token
|
||||
sensitiveValues.push(accessToken, refreshToken)
|
||||
recordPassed(phases, "AUTH_TOKEN_ACQUISITION", startedAt, "Authorization code and PKCE token exchange passed")
|
||||
|
||||
if (activeFault?.effect === "refresh-expired") {
|
||||
startedAt = Date.now()
|
||||
const refreshForm = new URLSearchParams({
|
||||
grant_type: "refresh_token",
|
||||
client_id: clientId,
|
||||
refresh_token: refreshToken,
|
||||
})
|
||||
if (tokenAuthMethod === "client_secret_post") refreshForm.set("client_secret", clientSecret)
|
||||
const refreshResponse = await fetchStep(tokenEndpoint, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: refreshForm,
|
||||
}, "CONTINUITY_REFRESH", overallDeadline)
|
||||
if (refreshResponse.ok) {
|
||||
await discardResponseBody(refreshResponse, "CONTINUITY_REFRESH", "oauth_credential_expired")
|
||||
throw new ProbeFailure("CONTINUITY_REFRESH", "oauth_refresh_unexpected_success", "Refresh unexpectedly succeeded after the mock credential expired")
|
||||
}
|
||||
const message = await safeHttpErrorMessage(refreshResponse, "CONTINUITY_REFRESH", "oauth_credential_expired")
|
||||
throw new ProbeFailure("CONTINUITY_REFRESH", "oauth_credential_expired", `${message} Reauthorization is required.`)
|
||||
}
|
||||
|
||||
const rpcHeaders = {
|
||||
authorization: `Bearer ${accessToken}`,
|
||||
accept: "application/json, text/event-stream",
|
||||
"content-type": "application/json",
|
||||
origin: baseUrl.origin,
|
||||
}
|
||||
startedAt = Date.now()
|
||||
const initializeRawResponse = await fetchStep(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: rpcHeaders,
|
||||
body: JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: scenario.protocol.version,
|
||||
capabilities: {},
|
||||
clientInfo: { name: "enterprise-mcp-probe", version: "0.1.0" },
|
||||
},
|
||||
}),
|
||||
}, "MCP_INITIALIZE", overallDeadline)
|
||||
if (initializeRawResponse.status === 401 || initializeRawResponse.status === 403) {
|
||||
throw new ProbeFailure(
|
||||
"AUTH_RESOURCE_VALIDATION",
|
||||
initializeRawResponse.status === 403 ? "oauth_insufficient_scope" : "oauth_wrong_audience",
|
||||
`MCP resource rejected the synthetic access token with HTTP ${initializeRawResponse.status}`,
|
||||
)
|
||||
}
|
||||
const initializeResponse = await expectOk(initializeRawResponse, "MCP_INITIALIZE")
|
||||
sessionId = initializeResponse.headers.get("mcp-session-id") ?? ""
|
||||
negotiatedProtocolHeader = initializeResponse.headers.get("mcp-protocol-version") ?? scenario.protocol.version
|
||||
const initializeEnvelope = await parseRpc(initializeResponse, "MCP_INITIALIZE")
|
||||
if (initializeEnvelope.error) {
|
||||
const versionEvidence = z.object({ supportedVersions: z.array(z.string()).min(1) }).safeParse(initializeEnvelope.error.data)
|
||||
throw versionEvidence.success || initializeEnvelope.error.message === "Unsupported MCP protocol version"
|
||||
? new ProbeFailure("MCP_VERSION", "mcp_version", initializeEnvelope.error.message)
|
||||
: new ProbeFailure("MCP_INITIALIZE", "mcp_initialize", initializeEnvelope.error.message)
|
||||
}
|
||||
if (initializeEnvelope.id !== 1) {
|
||||
throw new ProbeFailure("MCP_INITIALIZE", "mcp_initialize", "Initialize response JSON-RPC id did not match the request")
|
||||
}
|
||||
const initialize = parseAt(
|
||||
initializeResultSchema,
|
||||
initializeEnvelope.result,
|
||||
"MCP_INITIALIZE",
|
||||
"mcp_initialize",
|
||||
"Initialize result did not match the required shape",
|
||||
)
|
||||
if (initialize.protocolVersion !== scenario.protocol.version) {
|
||||
throw new ProbeFailure("MCP_VERSION", "mcp_version", "Server selected an unexpected MCP protocol version")
|
||||
}
|
||||
mutable.negotiatedProtocolVersion = initialize.protocolVersion
|
||||
if (scenario.protocol.requireSession && !sessionId) {
|
||||
throw new ProbeFailure("MCP_INITIALIZE", "mcp_initialize", "Initialize response omitted required MCP-Session-Id")
|
||||
}
|
||||
recordPassed(phases, "MCP_INITIALIZE", startedAt, "MCP version, capabilities, and session negotiated")
|
||||
|
||||
const sessionHeaders = {
|
||||
...rpcHeaders,
|
||||
"mcp-session-id": sessionId,
|
||||
"mcp-protocol-version": initialize.protocolVersion,
|
||||
}
|
||||
startedAt = Date.now()
|
||||
const initializedResponse = await fetchStep(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: sessionHeaders,
|
||||
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
|
||||
}, "MCP_INITIALIZED", overallDeadline)
|
||||
await discardResponseBody(initializedResponse, "MCP_INITIALIZED", "mcp_lifecycle")
|
||||
if (initializedResponse.status === 404) {
|
||||
throw new ProbeFailure("CONTINUITY_SESSION", "mcp_session_expired", "MCP session expired after initialize")
|
||||
}
|
||||
if (initializedResponse.status !== 202) {
|
||||
throw new ProbeFailure("MCP_INITIALIZED", "mcp_lifecycle", `Initialized notification returned HTTP ${initializedResponse.status}`)
|
||||
}
|
||||
recordPassed(phases, "MCP_INITIALIZED", startedAt, "Initialized notification received HTTP 202")
|
||||
|
||||
startedAt = Date.now()
|
||||
const toolNames = new Set<string>()
|
||||
const discoveredTools: MockTool[] = []
|
||||
const cursors = new Set<string>()
|
||||
let cursor: string | undefined
|
||||
let catalogComplete = false
|
||||
for (let page = 0; page < 25; page += 1) {
|
||||
if (cursor) {
|
||||
if (cursors.has(cursor)) throw new ProbeFailure("MCP_TOOL_DISCOVERY", "mcp_pagination_loop", "Tool catalog repeated a cursor")
|
||||
cursors.add(cursor)
|
||||
}
|
||||
const listRawResponse = await fetchStep(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: sessionHeaders,
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: 10 + page, method: "tools/list", params: cursor ? { cursor } : {} }),
|
||||
}, "MCP_TOOL_DISCOVERY", overallDeadline)
|
||||
if (listRawResponse.status === 403) {
|
||||
const message = await safeHttpErrorMessage(listRawResponse, "PROVIDER_AUTHORIZATION", "provider_per_user_403")
|
||||
throw new ProbeFailure("PROVIDER_AUTHORIZATION", "provider_per_user_403", `${message} (HTTP 403)`)
|
||||
}
|
||||
const listResponse = await expectOk(listRawResponse, "MCP_TOOL_DISCOVERY")
|
||||
const envelope = await parseRpc(listResponse, "MCP_TOOL_DISCOVERY")
|
||||
if (envelope.id !== 10 + page) {
|
||||
throw new ProbeFailure("MCP_TOOL_DISCOVERY", "mcp_tools_discovery", "tools/list response JSON-RPC id did not match the request")
|
||||
}
|
||||
if (envelope.error) throw new ProbeFailure("MCP_TOOL_DISCOVERY", "mcp_tools_discovery", envelope.error.message)
|
||||
const result = parseAt(
|
||||
toolsListResultSchema,
|
||||
envelope.result,
|
||||
"MCP_TOOL_DISCOVERY",
|
||||
"mcp_tools_discovery",
|
||||
"tools/list result did not match the required shape",
|
||||
)
|
||||
if (result.nextCursor && cursors.has(result.nextCursor)) {
|
||||
throw new ProbeFailure("MCP_TOOL_DISCOVERY", "mcp_pagination_loop", "Tool catalog repeated a cursor")
|
||||
}
|
||||
for (const rawTool of result.tools) {
|
||||
if (toolNames.has(rawTool.name)) throw new ProbeFailure("MCP_TOOL_DISCOVERY", "mcp_duplicate_tool", `Tool '${rawTool.name}' was duplicated`)
|
||||
const inputSchema = toolInputSchemaSchema.safeParse(rawTool.inputSchema)
|
||||
if (!inputSchema.success) throw new ProbeFailure("MCP_TOOL_DISCOVERY", "mcp_invalid_tool_schema", `Tool '${rawTool.name}' has an invalid input schema`)
|
||||
toolNames.add(rawTool.name)
|
||||
const sourceTool = profile.tools.find((tool) => tool.name === rawTool.name)
|
||||
if (sourceTool) discoveredTools.push(sourceTool)
|
||||
}
|
||||
if (!result.nextCursor) {
|
||||
catalogComplete = true
|
||||
break
|
||||
}
|
||||
cursor = result.nextCursor
|
||||
}
|
||||
if (!catalogComplete) {
|
||||
throw new ProbeFailure("MCP_TOOL_DISCOVERY", "mcp_pagination_limit", "Tool catalog exceeded the 25-page safety limit")
|
||||
}
|
||||
mutable.toolCount = toolNames.size
|
||||
if (toolNames.size === 0) throw new ProbeFailure("MCP_TOOL_DISCOVERY", "catalog_empty", "Tool catalog was protocol-valid but did not satisfy enterprise readiness because it was empty")
|
||||
if (mode !== "connection-readiness") {
|
||||
const expectedToolNames = new Set(profile.tools.map((tool) => tool.name))
|
||||
const missing = [...expectedToolNames].filter((name) => !toolNames.has(name))
|
||||
const unexpected = [...toolNames].filter((name) => !expectedToolNames.has(name))
|
||||
if (missing.length > 0 || unexpected.length > 0) {
|
||||
throw new ProbeFailure(
|
||||
"MCP_TOOL_DISCOVERY",
|
||||
"profile_fixture_mismatch",
|
||||
`Catalog does not match pinned profile fixture ${profile.fixtureVersion}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
recordPassed(phases, "MCP_TOOL_DISCOVERY", startedAt, `Retrieved ${toolNames.size} unique tools with bounded pagination`)
|
||||
|
||||
const fault = activeFault
|
||||
const shouldCall = options.callTool !== undefined || mode === "safe-read" || fault?.phase === "PROVIDER_AUTHORIZATION" || fault?.phase === "PROVIDER_EXECUTION"
|
||||
if (shouldCall) {
|
||||
const selected = options.callTool
|
||||
? { name: options.callTool.name, arguments: options.callTool.arguments }
|
||||
: (() => {
|
||||
const mutationRequired = fault?.effect === "commit-then-disconnect"
|
||||
const tool = discoveredTools.find((candidate) => candidate.kind === (mutationRequired ? "mutation" : "read"))
|
||||
if (!tool) throw new ProbeFailure("MCP_TOOL_EXECUTION", "mcp_tool", "No suitable tool was available for the requested probe")
|
||||
return { name: tool.name, arguments: defaultArguments(tool.inputSchema) }
|
||||
})()
|
||||
const selectedTool = profile.tools.find((tool) => tool.name === selected.name)
|
||||
if (mode === "safe-read" && selectedTool?.kind !== "read") {
|
||||
throw new ProbeFailure("CONFIGURATION", "configuration", "safe-read mode accepts only a declared read-only tool")
|
||||
}
|
||||
startedAt = Date.now()
|
||||
let toolResponse: Response
|
||||
try {
|
||||
toolResponse = await fetchStep(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: sessionHeaders,
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: 100, method: "tools/call", params: selected }),
|
||||
}, "MCP_TOOL_EXECUTION", overallDeadline)
|
||||
} catch {
|
||||
throw new ProbeFailure(
|
||||
selectedTool?.kind === "mutation" ? "PROVIDER_EXECUTION" : "MCP_TOOL_EXECUTION",
|
||||
selectedTool?.kind === "mutation" ? "mutation_indeterminate" : "mcp_tool",
|
||||
"Connection closed before the tool response completed",
|
||||
)
|
||||
}
|
||||
const envelope = await parseRpc(await expectOk(toolResponse, "MCP_TOOL_EXECUTION"), "MCP_TOOL_EXECUTION")
|
||||
if (envelope.id !== 100) {
|
||||
throw new ProbeFailure("MCP_TOOL_EXECUTION", "mcp_tool", "tools/call response JSON-RPC id did not match the request")
|
||||
}
|
||||
if (envelope.error) throw new ProbeFailure("MCP_TOOL_EXECUTION", "mcp_tool", envelope.error.message)
|
||||
const toolResult = parseAt(
|
||||
z.object({ isError: z.boolean(), structuredContent: z.unknown().optional() }),
|
||||
envelope.result,
|
||||
"MCP_TOOL_EXECUTION",
|
||||
"mcp_tool",
|
||||
"Tool response did not match the MCP result shape",
|
||||
)
|
||||
if (toolResult.isError) {
|
||||
throw classifyProviderToolError(toolResult.structuredContent)
|
||||
}
|
||||
recordPassed(phases, "MCP_TOOL_EXECUTION", startedAt, "Safe synthetic tool execution passed")
|
||||
}
|
||||
|
||||
await cleanup(true)
|
||||
const observed: ProbeResult["observed"] = { outcome: "success", firstFailedPhase: null, category: null }
|
||||
const ok = scenario.expected.outcome === "success"
|
||||
return {
|
||||
ok,
|
||||
diagnosticId,
|
||||
mode,
|
||||
expected: scenario.expected,
|
||||
observed,
|
||||
phases,
|
||||
negotiatedProtocolVersion: mutable.negotiatedProtocolVersion,
|
||||
toolCount: mutable.toolCount,
|
||||
error: null,
|
||||
}
|
||||
} catch (unknownError) {
|
||||
const failure = unknownError instanceof ProbeFailure
|
||||
? unknownError
|
||||
: new ProbeFailure("HTTP_ROUTING", "mcp_transport", unknownError instanceof Error ? unknownError.message : "Unknown probe failure")
|
||||
await cleanup(false)
|
||||
const safeFailureMessage = redactProbeMessage(failure.message, sensitiveValues)
|
||||
phases.push({ phase: failure.phase, status: "failed", elapsedMs: 0, summary: safeFailureMessage })
|
||||
const observed: ProbeResult["observed"] = {
|
||||
outcome: "failure",
|
||||
firstFailedPhase: failure.phase,
|
||||
category: failure.category,
|
||||
}
|
||||
const ok =
|
||||
scenario.expected.outcome === "failure" &&
|
||||
scenario.expected.firstFailedPhase === failure.phase &&
|
||||
scenario.expected.category === failure.category
|
||||
return {
|
||||
ok,
|
||||
diagnosticId,
|
||||
mode,
|
||||
expected: scenario.expected,
|
||||
observed,
|
||||
phases,
|
||||
negotiatedProtocolVersion: mutable.negotiatedProtocolVersion,
|
||||
toolCount: mutable.toolCount,
|
||||
error: { phase: failure.phase, category: failure.category, messageSafe: safeFailureMessage },
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)) }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"rootDir": ".",
|
||||
"outDir": "dist",
|
||||
"declaration": true,
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
Reference in new issue
Block a user