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

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

No files matched your search

@@ -0,0 +1,38 @@
# Reconciliation with earlier MCP diagnostic work
Reviewed 2026-07-12 against OpenWork PRs #2669, #2670, #2672, #2674, #2675,
and this package branch. The table distinguishes package behavior from Den
policy so the package does not absorb database, environment, or UI opinions.
| Earlier finding or practice | Reference implementation result | Owner |
| --- | --- | --- |
| Generic `failed to connect` / dropped cause | Operation and request phases retain the cause; Den #2669 produces the safe diagnostic envelope and reference. | Package + Den diagnostic adapter |
| Wrong OAuth callback public origin | Callback URI continues to come from validated Den public-origin configuration; the package accepts the URI as explicit input and never derives it from environment. | Den composition root |
| Token exchange succeeded but resource/MCP rejected it | Callback performs authenticated MCP initialization; unusable tokens are invalidated. | Package |
| Timed-out work wrote credentials later | Every port write carries an absolute commit deadline; Den checks inside a transaction and again before commit so throwing rolls back. | Contract + Den persistence adapter |
| One PKCE verifier was clobbered by concurrent Connect attempts | State-bound encrypted authorization transactions coexist up to a fixed cap and commit single-use. | Contract + Den persistence adapter |
| Concurrent DCR attempts selected different clients | Persistence is first-writer-wins; a losing SDK registration is rejected rather than used with the winner's stored state. Client revision is bound into authorization. | Contract + Den persistence adapter |
| Callback used stale in-memory credentials | Credential loads refresh the scoped Den record; callback MCP validation observes the committed credential. | Den persistence adapter |
| Expiry was stored but not part of the contract | Token, client-secret, authorization, lifecycle, and documentation expirations are explicit and validated. | Package contract |
| Refresh response omitted a rotated refresh token | The package preserves the existing refresh token only on the refresh path. | Package |
| 401 credential failure and 403 provider permission were confused | Den's structured HTTP diagnostics keep resource authentication separate from provider authorization. | Merged Den diagnostics |
| MCP `isError` looked successful | `isError: true` throws a typed provider-operation error with only allowlisted status/category/request-id signals. | Package |
| Unbounded response/catalog/SSE/redirect behavior | Catalog limits live in the package; guarded redirect, response/SSE size, cross-origin secret stripping, and body cancellation remain mandatory injected network policy. | Package + Den network adapter |
| Deleting a connection raced credential work | Delete and enterprise credential transactions lock the same connection row and clean dependent credentials/client state atomically. | Den persistence layer |
| Catalog Ready was mistaken for provider readiness | This package reports successful catalog retrieval only. The mock/test UI must continue to label operation/mutation readiness separately. | Mock/UI PR, not this package |
| Live timeline, retention, reconnect replay, support bundle | Package events are safe inputs; persistence, SSE, retention, and support access remain the separate live-diagnostics feature. | #2672, outside package |
| Mock controls, realistic ServiceNow/Microsoft fixtures | Used as the next conformance gate; not copied into the production client package. | Enterprise mock package/EE app |
| Proof viewer mobile/accessibility issues | No UI exists in this server/package PR. | Outside scope |
## Explicitly not collapsed into the package
- databases, tables, encryption keys, organization/member types;
- process environment or Helm/Docker parsing;
- admin/member route authorization and UI state;
- provider-specific ServiceNow/Microsoft product availability or scopes;
- support-bundle retention/access policy;
- mutation approval and provider idempotency policy.
Those concerns are required at their named adapter or product boundary. Leaving
them out is inversion of control, not omission: the package defines what must
be supplied and fails when a required contract is absent.
+104
View File
@@ -0,0 +1,104 @@
# `@openwork/enterprise-mcp-client`
Reference implementation for server-side remote MCP consumption in OpenWork.
The package owns the provider-neutral MCP/OAuth lifecycle. A composition root
supplies networking, persistence, tenancy/authorization, diagnostics, and the
clock. Den is one adapter; it is not embedded in the package architecture.
Den uses this package as its single runtime for new and existing MCP
connections. Existing OAuth registrations retain their stored callback URL;
new registrations use Den's deployment-wide shared callback.
## Reference architecture
```text
Den routes and capability authorization composition root
│
▼
enterprise MCP client API application package
│ │ │
▼ ▼ ▼
network OAuth ports diagnostics injected contracts
│ │
▼ ▼
guarded fetch encrypted Den DB adapter infrastructure adapters
```
Dependency direction always points inward. The package does not import Den
routes, database schemas, organization/member types, deployment configuration,
or environment variables.
The public OAuth persistence contract is split into three narrow ports:
- `clientRegistrations`: validated pre-registered or dynamically registered
clients with an opaque compare-and-swap revision and explicit expiry;
- `authorizations`: state-bound, expiring PKCE transactions that are loaded
without consumption; and
- `credentials`: token load/save/invalidation, including an atomic callback
commit that consumes the matching authorization transaction.
Every persistence write receives an absolute `commitExpiresAt` and abort
signal. An adapter must reject or roll back a transaction that cannot commit
inside that lifecycle. This prevents the system from reporting a timeout and
then silently writing credentials afterward.
## Security invariants
- Outbound `fetch` is mandatory injection. There is no global-fetch fallback.
Den supplies the redirect-safe SSRF/DNS-rebinding guard for the MCP endpoint,
OAuth discovery, registration, token endpoints, SSE, and tool calls.
- OAuth connect requires the caller's signed authorization id before network
or persistence work begins. No random-state fallback exists.
- PKCE transactions are state-bound, individually expiring, capped, encrypted
by Den, and consumed in the same database transaction as callback tokens.
- Callback token commit verifies the OAuth client revision, authorization
revision, connection identity, member/shared ownership, and lifecycle.
- Dynamic client registration is first-writer-wins. A losing concurrent DCR
cannot silently continue with the wrong client.
- Den supplies `application_type: web`, a deployment client-metadata URL, an
exact authorization-server issuer binding, and the administrator-approved
scope set. The SDK chooses pre-registration, client metadata, then DCR.
- `discoverConnectionRequirements` performs bounded, side-effect-free MCP,
protected-resource, authorization-server, and unauthenticated tool discovery.
It never performs DCR or writes application state.
- `scopes_supported` is treated as an availability declaration while an
administrator or challenge selects scopes. When neither selects any, the
client falls back to the provider-advertised set so providers with a
scope-less challenge still receive a usable authorization request. It
includes `offline_access` only when refresh support is advertised.
- New DCR client secrets are stored only in Den's encrypted client-secret
column. Unencrypted JSON metadata excludes `client_secret` and
`registration_access_token`.
- Access-token and client-secret expiration are absolute, validated values.
An expired access token without a refresh token is invalidated and reported
as reconnect-required. Refresh-token rotation preserves the previous refresh
token when a valid provider omits it from the refresh response. Refresh
commits compare the credential revision so a stale concurrent response cannot
overwrite newer rotated credentials.
- MCP `isError: true` is a failed provider operation, not a successful request.
- Tool catalogs have page, item, cursor, name, schema depth, schema size, and
aggregate-byte ceilings.
- Diagnostic events contain phases, outcome, duration, and HTTP status only.
They never contain tokens, API keys, codes, PKCE verifiers, URLs, tool
arguments, provider bodies, or customer content; a failing sink is isolated.
- Connection deletion and enterprise credential commits take the same Den row
lock, so deletion and a late callback have one deterministic winner.
See [SECURITY.md](./SECURITY.md) for the expiration/validation contract and
[PRIOR-FINDINGS.md](./PRIOR-FINDINGS.md) for the earlier MCP findings that were
incorporated, delegated to Den, or intentionally kept outside this server-side
package.
## Runtime boundary
The package covers Den's outbound server-side remote MCP client only. It does
not change local/direct engine MCP, the incoming OpenWork Cloud meta-MCP,
desktop UI, or provider-specific tenant administration.
Den uses this package as its only remote MCP OAuth runtime. New connections use
the deployment-wide shared callback. Existing connection rows retain their
stored callback mode and reconnect with that exact redirect URI, so no callback
migration, credential rewrite, or token copy is required. Version-one legacy
authorizations already in flight remain valid only through their original
per-connection callback and normal expiration window.
@@ -0,0 +1,74 @@
# Security, validation, and expiration contract
- Document status: active reference implementation
- Last code-and-document review: 2026-07-12
- Review by: 2026-10-12, or sooner when the MCP SDK/protocol baseline changes
Stable protocol evidence baseline: MCP 2025-11-25; provider support must still
be verified against the deployed ServiceNow or Microsoft surface.
This document is intentionally time-bounded. A reviewer must re-check the live
SDK, MCP specification, provider documentation, and Den adapter before changing
the review date. A date alone is not evidence of provider conformance.
## Required composition contracts
| Boundary | Package requirement | Den responsibility |
| --- | --- | --- |
| Network | A fetch port is required; all requests share cancellation/deadline signals. | Enforce protocol, credentials, DNS/IP policy, redirects, downgrade rules, cross-origin secret stripping, proxy/TLS posture, response limits, and body cancellation. |
| Clock | Absolute epoch-millisecond values; finite/non-negative validation. | Supply deployment time; monitor clock skew operationally. |
| Tenant and actor | No tenant/member model in the package. | Construct an adapter already scoped to exactly one organization, connection, and shared/member credential owner. |
| Client registration | Opaque revision, source, and expiry. Concurrent DCR is first-writer-wins. | Encrypt the secret, omit secrets from JSON metadata, serialize competing writers, and reject a losing client. |
| Authorization | Signed id, verifier, expiry, optional client revision, opaque transaction revision. | Store only a non-reversible state key plus encrypted verifier; cap transactions and enforce single-use. |
| Credentials | Validated OAuth token wire value plus absolute expiry and opaque revision. | Encrypt tokens and atomically persist/consume under connection and identity locks. |
| Diagnostics | Secret-free phase events; observer failures cannot affect behavior. | Add safe classification, correlation reference, authorized support evidence, retention, and audit. |
## Expiration rules
| Record | Validation | Expired behavior |
| --- | --- | --- |
| Operation lifecycle | `now < commitExpiresAt` before and immediately before transaction commit; abort signal remains active. | Reject/roll back with `MCP_LIFECYCLE_DEADLINE`; never commit after a reported timeout. |
| OAuth authorization/PKCE | Absolute expiry, signed state id, transaction revision, client revision; Den state verification is an additional outer check. | Delete the transaction and require Connect to restart. It cannot be reused. |
| Access token | Persist absolute expiry computed from `expires_in`; reject invalid/negative lifetimes. | With a refresh token, allow the bounded SDK refresh path. Without one, invalidate and require reconnect. |
| Refresh token | Opaque; provider rotation is authoritative. | Preserve the previous refresh token only when a successful refresh response validly omits a replacement. Invalid grant is reconnect-required, not generic retry. |
| OAuth client/client secret | Absolute `client_secret_expires_at` when declared; `0` means no declared expiry per DCR convention. | Invalidate and require client renewal/re-registration. Do not silently use an expired secret. |
| Documentation/provider assumptions | `Last review` and `Review by` above. | Revalidate against primary sources and a nonproduction tenant; never promote a stale preview/patch assumption. |
The default clock-skew allowance is 30 seconds and is configurable only at
client construction. It is not an environment read inside the package.
## Validation and failure ownership
Validation happens before secrets cross a boundary whenever possible:
- configuration: non-empty ids, HTTP(S) URLs, no URL credentials/fragments,
bounded OAuth state/code, positive timeouts and TTLs;
- persistence: OAuth wire schemas, opaque revisions, finite expirations,
matching authorization/client revisions, correct credential identity;
- protocol: initialize first, bounded complete pagination, tool schemas,
provider `isError`, close within deadline;
- adapter: tenant/member scope, encrypted columns, same-row transaction locks,
safe public origin, and guarded outbound requests.
Stable package codes distinguish missing/expired authorization, changed/expired
client registration, expired credentials, invalid persistence, and lifecycle
deadline. Den maps those codes to a safe phase, owner, remediation, and
diagnostic reference. Raw provider messages are not the administrator contract.
## Known evidence boundary
The deterministic OAuth/MCP tests prove protocol and port semantics. They do
not prove a real customer's ServiceNow ACL/domain policy, Microsoft consent or
Conditional Access, provider licensing/preview availability, egress allowlist,
or mutation behavior. Those remain explicit nonproduction conformance gates.
Pre-existing records written by another implementation may contain historical
provider metadata in the generic JSON column. This package never writes OAuth
client secrets or registration access tokens there. A separate reviewed data
cleanup is required before claiming that historical rows were rewritten; this
PR does not silently mutate every existing record at startup.
Pending PKCE data is intentionally not cross-mode compatible: current mode has
one unbound verifier, while enterprise mode has a versioned collection of
state-bound transactions. Feature-flag rollout/rollback must drain or expire
in-flight browser authorizations first. The adapter fails closed instead of
guessing a transaction identity for an old verifier.
@@ -0,0 +1,34 @@
{
"name": "@openwork/enterprise-mcp-client",
"private": true,
"version": "0.1.0",
"description": "Package-first remote MCP client runtime for enterprise Den connections",
"type": "module",
"exports": {
".": {
"types": "./src/index.ts",
"development": "./src/index.ts",
"default": "./dist/index.js"
}
},
"files": [
"dist",
"src"
],
"scripts": {
"build": "tsup",
"test": "tsx --test test/*.test.ts",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@modelcontextprotocol/core": "^2.0.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/node": "^20.11.30",
"tsx": "^4.23.1",
"tsup": "^8.5.0",
"typescript": "^5.6.3"
}
}
@@ -0,0 +1,115 @@
import { EnterpriseMcpOAuthContractError } from "./errors.js"
import { isAuthorizationServerDiscoveryBound } from "./oauth-discovery-binding.js"
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
function optionalString(value: unknown): string | undefined {
return typeof value === "string" && value.length > 0 ? value : undefined
}
export type McpAuthorizationResponseMixUpDefense =
| "response-issuer"
| "distinct-redirect-uri"
| "pinned-transaction"
| "legacy"
export type McpAuthorizationResponseIssuerValidation = {
defense: McpAuthorizationResponseMixUpDefense
ignoredResponseIssuer?: string
}
/**
* Validate the OAuth mix-up defense before a code is sent to a token endpoint
* or a provider error is acted upon. Shared callbacks normally use RFC 9207
* issuer identification. A caller may instead prove an issuer-specific
* redirect URI per RFC 9700, or explicitly select the narrower
* pinned-transaction compatibility posture after verifying a signed,
* expiring state token that binds the connection, callback mode, and selected
* issuer to a single-use server-side authorization record. Exact issuer
* comparisons are never normalized.
*/
export function validateMcpAuthorizationResponseIssuer(input: {
expectedIssuer?: string | null
discoveryState?: unknown
/** Undefined means the response omitted `iss`; an empty value is present and invalid. */
responseIssuer?: string
mixUpDefense?: McpAuthorizationResponseMixUpDefense
}): McpAuthorizationResponseIssuerValidation {
const discovery = isRecord(input.discoveryState) ? input.discoveryState : undefined
const authorizationServerMetadata = isRecord(discovery?.authorizationServerMetadata)
? discovery.authorizationServerMetadata
: undefined
const resourceMetadata = isRecord(discovery?.resourceMetadata)
? discovery.resourceMetadata
: undefined
const metadataIssuer = optionalString(authorizationServerMetadata?.issuer)
const discoveryIssuer = optionalString(discovery?.authorizationServerUrl)
const expectedIssuer = input.expectedIssuer ?? metadataIssuer ?? discoveryIssuer
if (!expectedIssuer) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_CONFIGURATION_REQUIRED",
"The OAuth authorization response cannot be validated without a bound authorization-server issuer.",
)
}
const advertisedIssuers = Array.isArray(resourceMetadata?.authorization_servers)
? resourceMetadata.authorization_servers.filter((value): value is string => typeof value === "string")
: undefined
const discoveryIsBound = discoveryIssuer
? isAuthorizationServerDiscoveryBound({
authorizationServerUrl: discoveryIssuer,
authorizationServerMetadata: metadataIssuer ? { issuer: metadataIssuer } : undefined,
resourceMetadata: resourceMetadata
? {
resource: optionalString(resourceMetadata.resource),
authorization_servers: advertisedIssuers,
}
: undefined,
}, expectedIssuer)
: (metadataIssuer === undefined || metadataIssuer === expectedIssuer)
&& (advertisedIssuers === undefined || advertisedIssuers.includes(expectedIssuer))
if (!discoveryIsBound) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The stored OAuth discovery state no longer matches the issuer bound to this MCP connection.",
)
}
if (input.responseIssuer !== undefined) {
if (input.responseIssuer !== expectedIssuer) {
if (
input.mixUpDefense === "distinct-redirect-uri"
&& authorizationServerMetadata?.authorization_response_iss_parameter_supported !== true
) {
return {
defense: "distinct-redirect-uri",
ignoredResponseIssuer: input.responseIssuer,
}
}
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The OAuth authorization response issuer does not match the issuer selected for this MCP connection.",
)
}
return { defense: input.mixUpDefense ?? "response-issuer" }
}
if (authorizationServerMetadata?.authorization_response_iss_parameter_supported === true) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The OAuth authorization response omitted the issuer required by the authorization-server metadata.",
)
}
if ((input.mixUpDefense ?? "response-issuer") === "response-issuer") {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The shared OAuth callback requires an authorization-response issuer.",
)
}
return { defense: input.mixUpDefense ?? "legacy" }
}
@@ -0,0 +1,386 @@
import type {
Client,
Implementation,
OAuthDiscoveryState,
ServerCapabilities,
StoredOAuthClientInformation,
StoredOAuthTokens,
Tool,
} from "@modelcontextprotocol/client"
export type { StoredOAuthClientInformation, StoredOAuthTokens } from "@modelcontextprotocol/client"
/** Epoch milliseconds. The package never reads a database or environment clock. */
export type EnterpriseMcpEpochMs = number
export type EnterpriseMcpFetch = (url: string | URL, init?: RequestInit) => Promise<Response>
export interface EnterpriseMcpClock {
now(): EnterpriseMcpEpochMs
}
export type EnterpriseMcpLifecycle = {
expiresAt: EnterpriseMcpEpochMs
signal: AbortSignal
}
export type EnterpriseMcpPersistenceContext = {
connectionId: string
/**
* A persistence adapter must reject or roll back a write that cannot commit
* before this absolute deadline. Checking only before a database call is not
* sufficient because the operation may settle after its caller timed out.
*/
commitExpiresAt: EnterpriseMcpEpochMs
signal: AbortSignal
}
export type EnterpriseMcpOAuthClientRegistration = {
clientInformation: StoredOAuthClientInformation
/** Opaque adapter-owned compare-and-swap revision. */
revision: string
/** Absolute client/client-secret expiration, when the provider declares one. */
expiresAt?: EnterpriseMcpEpochMs
source: "pre-registered" | "client-metadata" | "dynamic"
}
export interface EnterpriseMcpOAuthClientRegistrationPort {
load(context: EnterpriseMcpPersistenceContext): Promise<EnterpriseMcpOAuthClientRegistration | undefined>
/**
* First-writer-wins for concurrent dynamic registration. Implementations
* return the winning record and never silently replace a different client.
*/
save(input: {
context: EnterpriseMcpPersistenceContext
clientInformation: StoredOAuthClientInformation
/** The redirect URI used for this client registration attempt. */
redirectUri: string
expiresAt?: EnterpriseMcpEpochMs
source: "client-metadata" | "dynamic"
}): Promise<EnterpriseMcpOAuthClientRegistration>
invalidate(input: {
context: EnterpriseMcpPersistenceContext
reason: "expired" | "provider-rejected"
}): Promise<void>
}
export interface EnterpriseMcpOAuthDiscoveryPort {
load(context: EnterpriseMcpPersistenceContext): Promise<OAuthDiscoveryState | undefined>
save(input: {
context: EnterpriseMcpPersistenceContext
state: OAuthDiscoveryState
}): Promise<void>
invalidate(input: {
context: EnterpriseMcpPersistenceContext
reason: "issuer-mismatch" | "provider-rejected"
}): Promise<void>
}
export type EnterpriseMcpOAuthCredential = {
tokens: StoredOAuthTokens
/** Absolute access-token expiration, computed when tokens are committed. */
expiresAt?: EnterpriseMcpEpochMs
/** Opaque adapter-owned compare-and-swap revision. */
revision: string
}
export type EnterpriseMcpOAuthAuthorizationHandle = {
id: string
/** Opaque single-use transaction revision. */
revision: string
expiresAt: EnterpriseMcpEpochMs
clientRegistrationRevision?: string
}
export interface EnterpriseMcpOAuthAuthorizationPort {
/**
* Persist a bounded PKCE transaction. The id is the caller's signed OAuth
* state and must be stored as a keyed hash or equivalent non-reversible key.
*/
begin(input: {
context: EnterpriseMcpPersistenceContext
id: string
codeVerifier: string
expiresAt: EnterpriseMcpEpochMs
clientRegistrationRevision?: string
}): Promise<void>
/** Load without consuming; successful token commit consumes atomically. */
load(input: {
context: EnterpriseMcpPersistenceContext
id: string
}): Promise<{ handle: EnterpriseMcpOAuthAuthorizationHandle; codeVerifier: string } | undefined>
invalidate(input: {
context: EnterpriseMcpPersistenceContext
id: string
reason: "expired" | "abandoned" | "provider-rejected"
}): Promise<void>
}
export interface EnterpriseMcpOAuthCredentialPort {
load(context: EnterpriseMcpPersistenceContext): Promise<EnterpriseMcpOAuthCredential | undefined>
/**
* For authorization-code commits, the adapter MUST atomically validate and
* consume `authorization`, validate `clientRegistrationRevision`, persist
* the tokens, and enforce `context.commitExpiresAt`. Refresh commits enforce
* the same lifecycle fence but do not consume an authorization transaction.
*/
save(input: {
context: EnterpriseMcpPersistenceContext
tokens: StoredOAuthTokens
expiresAt?: EnterpriseMcpEpochMs
source: "authorization-code" | "refresh"
authorization?: EnterpriseMcpOAuthAuthorizationHandle
clientRegistrationRevision?: string
/** Required for refresh commits; rejects a response based on stale tokens. */
expectedCredentialRevision?: string
}): Promise<void>
invalidate(input: {
context: EnterpriseMcpPersistenceContext
reason: "expired" | "provider-rejected" | "post-authorization-validation-failed"
}): Promise<void>
}
/** Application-owned ports. No database, tenant, or deployment shape leaks in. */
export type EnterpriseMcpOAuthPersistence = {
clientRegistrations: EnterpriseMcpOAuthClientRegistrationPort
credentials: EnterpriseMcpOAuthCredentialPort
authorizations: EnterpriseMcpOAuthAuthorizationPort
discovery?: EnterpriseMcpOAuthDiscoveryPort
}
export type EnterpriseMcpOAuthConfiguration = {
applicationType: "web" | "native"
clientMetadataUrl?: string
authorizationServerIssuer?: string
requestedScopes?: string[]
}
export type EnterpriseMcpRequestPhase =
| "endpoint-request"
| "oauth-resource-discovery"
| "oauth-server-discovery"
| "oauth-client-registration"
| "oauth-token-exchange"
| "oauth-token-refresh"
| "mcp-discovery"
| "mcp-initialize"
| "mcp-tool-discovery"
| "mcp-tool-execution"
| "mcp-resource-discovery"
| "mcp-resource-read"
| "unknown-request"
export type EnterpriseMcpOperationPhase =
| "configuration"
| "requirements-discovery"
| "connection-handshake"
| "authorization-callback"
| "protocol-initialize"
| "tool-discovery"
| "tool-execution"
| "resource-discovery"
| "resource-read"
| "shutdown"
export type EnterpriseMcpDiagnosticEvent =
| {
kind: "request" | "operation"
connectionId: string
operationPhase: EnterpriseMcpOperationPhase
requestPhase: EnterpriseMcpRequestPhase | null
outcome: "started" | "succeeded" | "failed"
durationMs?: number
httpStatus?: number
responseBodyExcerpt?: string
protocolEra?: "modern" | "legacy"
protocolVersion?: string
}
| {
kind: "credential-invalidation"
connectionId: string
operationPhase: EnterpriseMcpOperationPhase
requestPhase: EnterpriseMcpRequestPhase
httpStatus?: number
invalidToken: boolean
}
export type EnterpriseMcpDiagnosticSink = (event: EnterpriseMcpDiagnosticEvent) => void
export type EnterpriseMcpAuthorization =
| { type: "none" }
| { type: "api-key"; token: string }
| {
type: "oauth"
persistence: EnterpriseMcpOAuthPersistence
configuration?: EnterpriseMcpOAuthConfiguration
}
export type EnterpriseMcpConnection = {
id: string
serverUrl: string
authorization: EnterpriseMcpAuthorization
}
export type EnterpriseMcpConnectInput = {
connection: EnterpriseMcpConnection
redirectUri: string
/** Required only when OAuth must begin; normally a signed, expiring state. */
authorizationId?: string
}
export type EnterpriseMcpConnectResult =
| { status: "connected" }
| { status: "needs_auth"; authorizeUrl: string }
export type EnterpriseMcpCompleteAuthorizationInput = {
connection: EnterpriseMcpConnection
redirectUri: string
code: string
/** The exact signed state returned by the provider callback. */
authorizationId: string
}
export type EnterpriseMcpAbandonAuthorizationInput = {
connection: EnterpriseMcpConnection
authorizationId: string
reason: "provider-rejected" | "abandoned"
}
export type EnterpriseMcpListToolsInput = {
connection: EnterpriseMcpConnection
redirectUri: string
}
export type EnterpriseMcpCallToolInput = {
connection: EnterpriseMcpConnection
redirectUri: string
toolName: string
arguments: Record<string, unknown>
}
export type EnterpriseMcpListResourcesInput = {
connection: EnterpriseMcpConnection
redirectUri: string
}
export type EnterpriseMcpReadResourceInput = {
connection: EnterpriseMcpConnection
redirectUri: string
uri: string
}
export type EnterpriseMcpListResourceTemplatesInput = {
connection: EnterpriseMcpConnection
redirectUri: string
}
export type EnterpriseMcpToolResult = Awaited<ReturnType<Client["callTool"]>>
export type EnterpriseMcpTool = Omit<Tool, "inputSchema" | "outputSchema"> & {
inputSchema: Record<string, unknown>
outputSchema?: Record<string, unknown>
}
export type EnterpriseMcpResourceList = Awaited<ReturnType<Client["listResources"]>>["resources"]
export type EnterpriseMcpResourceTemplateList = Awaited<ReturnType<Client["listResourceTemplates"]>>["resourceTemplates"]
export type EnterpriseMcpResourceResult = Awaited<ReturnType<Client["readResource"]>>
export type EnterpriseMcpServerDescriptor = {
capabilities: ServerCapabilities
serverInfo?: Implementation
instructions?: string
}
export type EnterpriseMcpRequirementWarning = {
code: string
message: string
}
export type EnterpriseMcpManualRequirement = {
code: string
label: string
reason: string
required: boolean
}
export type EnterpriseMcpAuthorizationServerRequirement = {
issuer: string
authorizationEndpoint?: string
tokenEndpoint?: string
registrationEndpoint?: string
clientIdMetadataDocumentSupported: boolean
scopesSupported?: string[]
grantTypesSupported?: string[]
codeChallengeMethodsSupported?: string[]
tokenEndpointAuthMethodsSupported?: string[]
}
export type EnterpriseMcpConnectionRequirements = {
status: "ready" | "manual_action_required" | "unsupported" | "unreachable"
server: {
url: string
protocolEra?: "modern" | "legacy"
protocolVersion?: string
/** Protocol-negotiation status; the field name is retained for API compatibility. */
initialize: "succeeded" | "authentication_required" | "failed"
}
authentication: {
kind: "none" | "oauth" | "manual_bearer" | "unknown"
resource?: string
protectedResourceMetadataUrl?: string
authorizationServers: EnterpriseMcpAuthorizationServerRequirement[]
requiredScopes: string[]
recommendedScopes: string[]
refreshSupport: "supported" | "not_advertised" | "unknown"
availableRegistrationMethods: Array<"pre_registered" | "client_metadata" | "dynamic">
recommendedRegistrationMethod: "client_metadata" | "dynamic" | "pre_registered"
}
tools: {
visibility: "available_without_auth" | "requires_auth" | "unavailable"
count?: number
items?: Array<{
name: string
readOnlyHint?: boolean
destructiveHint?: boolean
openWorldHint?: boolean
}>
}
manualRequirements: EnterpriseMcpManualRequirement[]
warnings: EnterpriseMcpRequirementWarning[]
}
export type DiscoverEnterpriseMcpConnectionRequirementsInput = {
serverUrl: string
fetch: EnterpriseMcpFetch
timeoutMs?: number
maxAuthorizationServers?: number
maxTools?: number
}
export type EnterpriseMcpClientOptions = {
/**
* Required outbound port. The composition root owns SSRF, DNS rebinding,
* proxy, TLS, redirect, response-size, and secret-forwarding policy.
*/
fetch: EnterpriseMcpFetch
clock?: EnterpriseMcpClock
diagnosticSink?: EnterpriseMcpDiagnosticSink
operationTimeoutMs?: number
closeTimeoutMs?: number
authorizationTransactionTtlMs?: number
expirationSkewMs?: number
clientName?: string
clientVersion?: string
lifecycle?: EnterpriseMcpLifecycle
}
export interface EnterpriseMcpClient {
connect(input: EnterpriseMcpConnectInput): Promise<EnterpriseMcpConnectResult>
completeAuthorization(input: EnterpriseMcpCompleteAuthorizationInput): Promise<void>
abandonAuthorization(input: EnterpriseMcpAbandonAuthorizationInput): Promise<void>
listTools(input: EnterpriseMcpListToolsInput): Promise<EnterpriseMcpTool[]>
callTool(input: EnterpriseMcpCallToolInput): Promise<EnterpriseMcpToolResult>
callToolRaw(input: EnterpriseMcpCallToolInput): Promise<EnterpriseMcpToolResult>
listResources(input: EnterpriseMcpListResourcesInput): Promise<EnterpriseMcpResourceList>
readResource(input: EnterpriseMcpReadResourceInput): Promise<EnterpriseMcpResourceResult>
listResourceTemplates(input: EnterpriseMcpListResourceTemplatesInput): Promise<EnterpriseMcpResourceTemplateList>
describeServer(input: EnterpriseMcpListResourcesInput): Promise<EnterpriseMcpServerDescriptor>
}
@@ -0,0 +1,730 @@
import {
auth,
Client,
StreamableHTTPClientTransport,
UnauthorizedError,
} from "@modelcontextprotocol/client"
import type { RequestOptions } from "@modelcontextprotocol/client"
import { z } from "zod"
import type {
EnterpriseMcpAuthorization,
EnterpriseMcpAbandonAuthorizationInput,
EnterpriseMcpCallToolInput,
EnterpriseMcpClient,
EnterpriseMcpClientOptions,
EnterpriseMcpClock,
EnterpriseMcpCompleteAuthorizationInput,
EnterpriseMcpConnectInput,
EnterpriseMcpConnectResult,
EnterpriseMcpConnection,
EnterpriseMcpFetch,
EnterpriseMcpLifecycle,
EnterpriseMcpListResourcesInput,
EnterpriseMcpListResourceTemplatesInput,
EnterpriseMcpListToolsInput,
EnterpriseMcpOperationPhase,
EnterpriseMcpRequestPhase,
EnterpriseMcpReadResourceInput,
} from "./contracts.js"
import { EnterpriseMcpClientError, EnterpriseMcpLifecycleDeadlineError, EnterpriseMcpToolResultError } from "./errors.js"
import { EnterpriseMcpOAuthProvider } from "./oauth-provider.js"
import { createEnterpriseMcpRequestObserver, type EnterpriseMcpRequestObserver } from "./request-observer.js"
import { createEnterpriseMcpTokenResponseCompat } from "./token-response-compat.js"
import { collectEnterpriseMcpTools } from "./tool-catalog.js"
import {
assertEnterpriseMcpResourceResult,
collectEnterpriseMcpResources,
collectEnterpriseMcpResourceTemplates,
ENTERPRISE_MCP_RESOURCE_URI_LIMIT_BYTES,
} from "./resource-catalog.js"
import { assertEnterpriseMcpToolArguments } from "./tool-input.js"
const connectionSchema = z.object({
id: z.string().trim().min(1),
serverUrl: z.string().trim().url(),
})
const redirectUriSchema = z.string().trim().url()
const clientMetadataUrlSchema = z.string().trim().url().refine((value) => {
const url = new URL(value)
return url.protocol === "https:" && url.pathname !== "/"
}, "An OAuth client metadata document URL must use HTTPS and include a path.")
const oauthConfigurationSchema = z.object({
applicationType: z.enum(["web", "native"]),
clientMetadataUrl: clientMetadataUrlSchema.optional(),
authorizationServerIssuer: z.string().trim().url().optional(),
requestedScopes: z.array(z.string().trim().min(1)).max(128).optional(),
})
const toolNameSchema = z.string().trim().min(1)
const resourceUriSchema = z.string().trim().min(1).max(ENTERPRISE_MCP_RESOURCE_URI_LIMIT_BYTES).refine(
(value) => Buffer.byteLength(value, "utf8") <= ENTERPRISE_MCP_RESOURCE_URI_LIMIT_BYTES,
"MCP resource URIs must not exceed 16 KiB.",
)
const authorizationIdSchema = z.string().min(1).max(8 * 1024)
const authorizationCodeSchema = z.string().min(1).max(8 * 1024)
const DEFAULT_OPERATION_TIMEOUT_MS = 30_000
const DEFAULT_CLOSE_TIMEOUT_MS = 5_000
const DEFAULT_AUTHORIZATION_TRANSACTION_TTL_MS = 10 * 60_000
const DEFAULT_EXPIRATION_SKEW_MS = 30_000
const MCP_APP_EXTENSION = "io.modelcontextprotocol/ui"
const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app"
const optionsSchema = z.object({
operationTimeoutMs: z.number().int().positive(),
closeTimeoutMs: z.number().int().positive(),
authorizationTransactionTtlMs: z.number().int().positive(),
expirationSkewMs: z.number().int().nonnegative(),
clientName: z.string().trim().min(1).max(255),
clientVersion: z.string().trim().min(1).max(255),
})
type Session = {
client: Client
transport: StreamableHTTPClientTransport
serverUrl: URL
oauthProvider?: EnterpriseMcpOAuthProvider
observer: EnterpriseMcpRequestObserver
controller: AbortController
requestOptions: RequestOptions
lifecycle: EnterpriseMcpLifecycle
}
function requestInit(authorization: EnterpriseMcpAuthorization): RequestInit | undefined {
if (authorization.type !== "api-key") return undefined
return { headers: { authorization: `Bearer ${authorization.token}` } }
}
function validateConnection(connection: EnterpriseMcpConnection): URL {
const parsed = connectionSchema.parse({ id: connection.id, serverUrl: connection.serverUrl })
if (connection.authorization.type === "api-key" && !connection.authorization.token.trim()) {
throw new Error("An API key connection requires a non-empty token.")
}
const url = new URL(parsed.serverUrl)
if (url.protocol !== "https:" && url.protocol !== "http:") {
throw new Error("An enterprise MCP server URL must use HTTP or HTTPS.")
}
if (url.username || url.password) {
throw new Error("An enterprise MCP server URL cannot contain embedded credentials.")
}
if (url.hash) throw new Error("An enterprise MCP server URL cannot contain a fragment.")
return url
}
function validateRedirectUri(redirectUri: string): string {
const parsed = redirectUriSchema.parse(redirectUri)
const url = new URL(parsed)
if (url.protocol !== "https:" && url.protocol !== "http:") {
throw new Error("An enterprise MCP OAuth redirect URI must use HTTP or HTTPS.")
}
if (url.username || url.password || url.hash) {
throw new Error("An enterprise MCP OAuth redirect URI cannot contain credentials or a fragment.")
}
return parsed
}
function configurationValue<T>(parse: () => T): T {
try {
return parse()
} catch (error) {
throw new EnterpriseMcpClientError({
operationPhase: "configuration",
requestPhase: null,
cause: error,
})
}
}
async function closeWithinDeadline(close: () => Promise<void>, timeoutMs: number): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined
try {
await Promise.race([
close(),
new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => reject(new Error("The MCP client did not close before its deadline.")), timeoutMs)
}),
])
} finally {
if (timer) clearTimeout(timer)
}
}
export function createEnterpriseMcpClient(options: EnterpriseMcpClientOptions): EnterpriseMcpClient {
const parsedOptions = configurationValue(() => optionsSchema.parse({
operationTimeoutMs: options.operationTimeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS,
closeTimeoutMs: options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS,
authorizationTransactionTtlMs: options.authorizationTransactionTtlMs ?? DEFAULT_AUTHORIZATION_TRANSACTION_TTL_MS,
expirationSkewMs: options.expirationSkewMs ?? DEFAULT_EXPIRATION_SKEW_MS,
clientName: options.clientName ?? "OpenWork",
clientVersion: options.clientVersion ?? "1.0.0",
}))
const {
operationTimeoutMs,
closeTimeoutMs,
authorizationTransactionTtlMs,
expirationSkewMs,
clientName,
clientVersion,
} = parsedOptions
const explicitOperationTimeoutMs = options.operationTimeoutMs
const clock: EnterpriseMcpClock = options.clock ?? { now: () => Date.now() }
const configuredFetch: EnterpriseMcpFetch = options.fetch
function emitDiagnostic(event: Parameters<NonNullable<EnterpriseMcpClientOptions["diagnosticSink"]>>[0]): void {
try {
options.diagnosticSink?.(event)
} catch {
// Diagnostics must never change the connection outcome they observe.
}
}
function failureRequestPhase(observer: EnterpriseMcpRequestObserver) {
return observer.lastFailedRequestPhase() ?? observer.lastRequestPhase()
}
function isMcpResourceRequest(phase: EnterpriseMcpRequestPhase): boolean {
return phase === "mcp-discovery"
|| phase === "mcp-initialize"
|| phase === "mcp-tool-discovery"
|| phase === "mcp-tool-execution"
|| phase === "mcp-resource-discovery"
|| phase === "mcp-resource-read"
|| phase === "endpoint-request"
}
async function invalidateTerminallyRejectedCredential(
session: Session,
input: { connectionId: string; operationPhase: EnterpriseMcpOperationPhase },
): Promise<void> {
if (!session.oauthProvider || !["tool-execution", "resource-discovery", "resource-read"].includes(input.operationPhase)) return
const failure = session.observer.lastRequestFailure()
if (!failure || !isMcpResourceRequest(failure.requestPhase)) return
const rejected = (failure.httpStatus === 401 && failure.invalidToken)
|| (failure.httpStatus === 403 && (failure.bearerChallenge || failure.insufficientScope))
if (!rejected) return
await session.oauthProvider.invalidateCredentials("tokens")
emitDiagnostic({
kind: "credential-invalidation",
connectionId: input.connectionId,
operationPhase: input.operationPhase,
requestPhase: failure.requestPhase,
httpStatus: failure.httpStatus,
invalidToken: failure.invalidToken,
})
}
function createSession(input: {
connection: EnterpriseMcpConnection
redirectUri: string
flow: { kind: "connect"; authorizationId?: string } | { kind: "callback"; authorizationId: string } | { kind: "runtime" }
operationPhase: EnterpriseMcpOperationPhase
}): Session {
const serverUrl = validateConnection(input.connection)
const redirectUri = validateRedirectUri(input.redirectUri)
const oauthConfiguration = input.connection.authorization.type === "oauth"
? configurationValue(() => oauthConfigurationSchema.parse(
input.connection.authorization.type === "oauth"
? input.connection.authorization.configuration ?? { applicationType: "web" }
: { applicationType: "web" },
))
: undefined
const controller = new AbortController()
const configuredExpiresAt = options.lifecycle?.expiresAt ?? (clock.now() + operationTimeoutMs)
const remaining = Math.max(1, configuredExpiresAt - clock.now())
const maxRequestTimeoutMs = remaining > 1 ? remaining - 1 : remaining
const requestTimeoutMs = Math.max(1, Math.min(
options.lifecycle ? explicitOperationTimeoutMs ?? maxRequestTimeoutMs : operationTimeoutMs,
maxRequestTimeoutMs,
))
const timeout = setTimeout(() => {
controller.abort(new EnterpriseMcpLifecycleDeadlineError(input.operationPhase))
}, remaining)
controller.signal.addEventListener("abort", () => clearTimeout(timeout), { once: true })
const compatibleFetch = createEnterpriseMcpTokenResponseCompat({
fetch: configuredFetch,
onTranslation: (translation) => emitDiagnostic({
kind: "request",
connectionId: input.connection.id,
operationPhase: input.operationPhase,
requestPhase: translation.requestPhase,
outcome: translation.outcome,
httpStatus: translation.httpStatus,
responseBodyExcerpt: translation.responseBodyExcerpt,
}),
})
const observer = createEnterpriseMcpRequestObserver({
connectionId: input.connection.id,
operationPhase: input.operationPhase,
fetch: compatibleFetch,
diagnosticSink: options.diagnosticSink ? emitDiagnostic : undefined,
signal: options.lifecycle
? AbortSignal.any([controller.signal, options.lifecycle.signal])
: controller.signal,
clock,
})
const requestSignal = options.lifecycle
? AbortSignal.any([controller.signal, options.lifecycle.signal])
: controller.signal
const oauthProvider = input.connection.authorization.type === "oauth"
? new EnterpriseMcpOAuthProvider({
redirectUri,
connectionId: input.connection.id,
persistence: input.connection.authorization.persistence,
flow: input.flow,
clientName,
clock,
lifecycle: {
expiresAt: configuredExpiresAt,
signal: requestSignal,
},
authorizationTransactionTtlMs,
expirationSkewMs,
fetch: observer.fetch,
oauthConfiguration,
})
: undefined
const transport = new StreamableHTTPClientTransport(serverUrl, {
authProvider: oauthProvider,
fetch: observer.fetch,
requestInit: requestInit(input.connection.authorization),
})
const capabilities = {
extensions: {
[MCP_APP_EXTENSION]: { mimeTypes: [MCP_APP_MIME_TYPE] },
},
}
const client = new Client(
{ name: clientName, version: clientVersion },
{
capabilities,
versionNegotiation: { mode: "auto" },
},
)
const requestOptions: RequestOptions = {
signal: requestSignal,
timeout: requestTimeoutMs,
maxTotalTimeout: remaining,
resetTimeoutOnProgress: true,
onprogress: () => undefined,
}
return {
client,
transport,
serverUrl,
oauthProvider,
observer,
controller,
requestOptions,
lifecycle: { expiresAt: configuredExpiresAt, signal: requestSignal },
}
}
async function connectWithProtocolNegotiation(input: {
session: Session
connectionId: string
operationPhase: EnterpriseMcpOperationPhase
}): Promise<void> {
await input.session.client.connect(input.session.transport, input.session.requestOptions)
emitDiagnostic({
kind: "operation",
connectionId: input.connectionId,
operationPhase: input.operationPhase,
requestPhase: input.session.observer.lastRequestPhase(),
outcome: "succeeded",
protocolEra: input.session.client.getProtocolEra(),
protocolVersion: input.session.client.getNegotiatedProtocolVersion(),
})
}
async function runOperation<T>(input: {
connection: EnterpriseMcpConnection
redirectUri: string
flow: { kind: "connect"; authorizationId?: string } | { kind: "callback"; authorizationId: string } | { kind: "runtime" }
operationPhase: EnterpriseMcpOperationPhase
operation: (session: Session) => Promise<T>
}): Promise<T> {
let session: Session
try {
session = createSession(input)
} catch (error) {
throw new EnterpriseMcpClientError({
operationPhase: "configuration",
requestPhase: null,
cause: error,
})
}
emitDiagnostic({
kind: "operation",
connectionId: input.connection.id,
operationPhase: input.operationPhase,
requestPhase: null,
outcome: "started",
})
const startedAt = clock.now()
try {
const result = await input.operation(session)
emitDiagnostic({
kind: "operation",
connectionId: input.connection.id,
operationPhase: input.operationPhase,
requestPhase: session.observer.lastRequestPhase(),
outcome: "succeeded",
durationMs: clock.now() - startedAt,
})
return result
} catch (error) {
const wrapped = error instanceof EnterpriseMcpClientError
? error
: new EnterpriseMcpClientError({
operationPhase: input.operationPhase,
requestPhase: failureRequestPhase(session.observer),
cause: error,
})
emitDiagnostic({
kind: "operation",
connectionId: input.connection.id,
operationPhase: input.operationPhase,
requestPhase: failureRequestPhase(session.observer),
outcome: "failed",
durationMs: clock.now() - startedAt,
})
throw wrapped
} finally {
session.controller.abort()
}
}
async function runConnectedOperation<T>(input: {
connection: EnterpriseMcpConnection
redirectUri: string
operationPhase: EnterpriseMcpOperationPhase
operation: (session: Session) => Promise<T>
}): Promise<T> {
return runOperation({
...input,
flow: { kind: "runtime" },
operation: async (session) => {
try {
await connectWithProtocolNegotiation({
session,
connectionId: input.connection.id,
operationPhase: input.operationPhase,
})
let operationFailed = false
try {
return await input.operation(session)
} catch (error) {
operationFailed = true
throw error
} finally {
try {
await closeWithinDeadline(() => session.client.close(), closeTimeoutMs)
} catch (error) {
if (!operationFailed) {
throw new EnterpriseMcpClientError({
operationPhase: "shutdown",
requestPhase: session.observer.lastRequestPhase(),
cause: error,
})
}
}
}
} catch (error) {
await invalidateTerminallyRejectedCredential(session, {
connectionId: input.connection.id,
operationPhase: input.operationPhase,
})
throw error
}
},
})
}
return {
async connect(input: EnterpriseMcpConnectInput): Promise<EnterpriseMcpConnectResult> {
const authorizationId = configurationValue(() => input.authorizationId === undefined
? undefined
: authorizationIdSchema.parse(input.authorizationId))
if (input.connection.authorization.type === "oauth" && !authorizationId) {
throw new EnterpriseMcpClientError({
operationPhase: "configuration",
requestPhase: null,
cause: new Error("An OAuth connection requires a signed authorization transaction id."),
})
}
return runOperation({
connection: input.connection,
redirectUri: input.redirectUri,
flow: { kind: "connect", authorizationId },
operationPhase: "connection-handshake",
operation: async (session) => {
try {
const hadOAuthCredential = session.oauthProvider
? Boolean(await session.oauthProvider.tokens())
: false
await connectWithProtocolNegotiation({
session,
connectionId: input.connection.id,
operationPhase: "connection-handshake",
})
// Some providers allow protocol negotiation before challenging on tools/list.
// Probe only when the server advertised the tools capability: MCP
// servers are allowed to expose resources and/or prompts without
// implementing tools/list at all.
if (session.client.getServerCapabilities()?.tools) {
await session.client.listTools(undefined, session.requestOptions)
}
// OAuth connections must not be treated as member-connected merely
// because a provider exposes protocol negotiation and tools/list publicly.
// When no member credential exists, proactively run OAuth discovery
// so providers such as BigQuery can return an authorization URL
// without first issuing an MCP-level 401 challenge.
if (session.oauthProvider && !hadOAuthCredential) {
const authResult = await auth(session.oauthProvider, {
serverUrl: session.serverUrl,
fetchFn: session.observer.fetch,
})
const authorizeUrl = session.oauthProvider.authorizeUrl
if (authResult === "REDIRECT") {
if (!authorizeUrl) {
throw new Error("The OAuth provider requested authorization without an authorization URL.")
}
try {
await closeWithinDeadline(() => session.client.close(), closeTimeoutMs)
} catch {
// The bounded cleanup attempt must not discard a valid authorization URL.
}
return { status: "needs_auth", authorizeUrl }
}
}
try {
await closeWithinDeadline(() => session.client.close(), closeTimeoutMs)
} catch (error) {
throw new EnterpriseMcpClientError({
operationPhase: "shutdown",
requestPhase: session.observer.lastRequestPhase(),
cause: error,
})
}
return { status: "connected" }
} catch (error) {
const authorizeUrl = session.oauthProvider?.authorizeUrl ?? null
if (error instanceof UnauthorizedError && authorizeUrl) {
try {
await closeWithinDeadline(() => session.client.close(), closeTimeoutMs)
} catch {
// The bounded cleanup attempt must not discard a valid authorization URL.
}
return { status: "needs_auth", authorizeUrl }
}
throw error
}
},
})
},
async completeAuthorization(input: EnterpriseMcpCompleteAuthorizationInput): Promise<void> {
const authorizationId = configurationValue(() => authorizationIdSchema.parse(input.authorizationId))
const code = configurationValue(() => authorizationCodeSchema.parse(input.code))
await runOperation({
connection: input.connection,
redirectUri: input.redirectUri,
flow: { kind: "callback", authorizationId },
operationPhase: "authorization-callback",
operation: async (session) => {
const credentialPort = input.connection.authorization.type === "oauth"
? input.connection.authorization.persistence.credentials
: null
let exchangedTokens = false
let operationFailed = false
try {
await session.transport.finishAuth(code)
exchangedTokens = true
await connectWithProtocolNegotiation({
session,
connectionId: input.connection.id,
operationPhase: "authorization-callback",
})
if (session.client.getServerCapabilities()?.tools) {
await session.client.listTools(undefined, session.requestOptions)
}
} catch (error) {
operationFailed = true
let credentialCleanupError: unknown = null
if (exchangedTokens && credentialPort) {
try {
const cleanupController = new AbortController()
await credentialPort.invalidate({
context: {
connectionId: input.connection.id,
commitExpiresAt: clock.now() + closeTimeoutMs,
signal: cleanupController.signal,
},
reason: "post-authorization-validation-failed",
})
} catch (cleanupError) {
credentialCleanupError = cleanupError
}
}
if (credentialCleanupError) {
throw new EnterpriseMcpClientError({
operationPhase: "authorization-callback",
requestPhase: session.observer.lastRequestPhase(),
cause: new AggregateError(
[error, credentialCleanupError],
"Post-authorization validation failed and the exchanged credentials could not be invalidated.",
),
})
}
throw error
} finally {
try {
await closeWithinDeadline(() => session.client.close(), closeTimeoutMs)
} catch (error) {
if (!operationFailed) {
throw new EnterpriseMcpClientError({
operationPhase: "shutdown",
requestPhase: session.observer.lastRequestPhase(),
cause: error,
})
}
}
}
},
})
},
async abandonAuthorization(input: EnterpriseMcpAbandonAuthorizationInput): Promise<void> {
const authorizationId = configurationValue(() => authorizationIdSchema.parse(input.authorizationId))
if (input.connection.authorization.type !== "oauth") return
const controller = new AbortController()
const expiresAt = options.lifecycle?.expiresAt ?? (clock.now() + operationTimeoutMs)
await input.connection.authorization.persistence.authorizations.invalidate({
context: {
connectionId: input.connection.id,
commitExpiresAt: expiresAt,
signal: options.lifecycle
? AbortSignal.any([controller.signal, options.lifecycle.signal])
: controller.signal,
},
id: authorizationId,
reason: input.reason,
})
},
async listTools(input: EnterpriseMcpListToolsInput) {
return runConnectedOperation({
connection: input.connection,
redirectUri: input.redirectUri,
operationPhase: "tool-discovery",
operation: async (session) => {
return collectEnterpriseMcpTools({
requestOptions: session.requestOptions,
listPage: (cursor, options) => session.client.listTools(
cursor ? { cursor } : undefined,
options,
),
})
},
})
},
async callToolRaw(input: EnterpriseMcpCallToolInput) {
const toolName = configurationValue(() => toolNameSchema.parse(input.toolName))
configurationValue(() => assertEnterpriseMcpToolArguments(input.arguments))
return runConnectedOperation({
connection: input.connection,
redirectUri: input.redirectUri,
operationPhase: "tool-execution",
operation: async (session) => {
const result = await session.client.callTool({
name: toolName,
arguments: input.arguments,
}, session.requestOptions)
return result
},
})
},
async callTool(input: EnterpriseMcpCallToolInput) {
const toolName = configurationValue(() => toolNameSchema.parse(input.toolName))
configurationValue(() => assertEnterpriseMcpToolArguments(input.arguments))
return runConnectedOperation({
connection: input.connection,
redirectUri: input.redirectUri,
operationPhase: "tool-execution",
operation: async (session) => {
const result = await session.client.callTool({
name: toolName,
arguments: input.arguments,
}, session.requestOptions)
if ("isError" in result && result.isError) throw new EnterpriseMcpToolResultError(result)
return result
},
})
},
async listResources(input: EnterpriseMcpListResourcesInput) {
return runConnectedOperation({
connection: input.connection,
redirectUri: input.redirectUri,
operationPhase: "resource-discovery",
operation: (session) => collectEnterpriseMcpResources({
requestOptions: session.requestOptions,
listPage: (cursor, options) => session.client.listResources(
cursor ? { cursor } : undefined,
options,
),
}),
})
},
async readResource(input: EnterpriseMcpReadResourceInput) {
const uri = configurationValue(() => resourceUriSchema.parse(input.uri))
return runConnectedOperation({
connection: input.connection,
redirectUri: input.redirectUri,
operationPhase: "resource-read",
operation: async (session) => {
const result = await session.client.readResource({ uri }, session.requestOptions)
assertEnterpriseMcpResourceResult(result)
return result
},
})
},
async listResourceTemplates(input: EnterpriseMcpListResourceTemplatesInput) {
return runConnectedOperation({
connection: input.connection,
redirectUri: input.redirectUri,
operationPhase: "resource-discovery",
operation: (session) => collectEnterpriseMcpResourceTemplates({
requestOptions: session.requestOptions,
listPage: (cursor, options) => session.client.listResourceTemplates(
cursor ? { cursor } : undefined,
options,
),
}),
})
},
async describeServer(input: EnterpriseMcpListResourcesInput) {
return runConnectedOperation({
connection: input.connection,
redirectUri: input.redirectUri,
operationPhase: "protocol-initialize",
operation: async (session) => {
const instructions = session.client.getInstructions()
const serverInfo = session.client.getServerVersion()
return {
capabilities: session.client.getServerCapabilities() ?? {},
...(serverInfo ? { serverInfo } : {}),
...(instructions ? { instructions } : {}),
}
},
})
},
}
}
@@ -0,0 +1,226 @@
import { SdkError, SdkErrorCode } from "@modelcontextprotocol/client"
import type { EnterpriseMcpOperationPhase, EnterpriseMcpRequestPhase } from "./contracts.js"
export type EnterpriseMcpErrorCode =
| "MCP_CONFIGURATION_FAILED"
| "MCP_REQUIREMENTS_DISCOVERY_FAILED"
| "MCP_CONNECTION_HANDSHAKE_FAILED"
| "MCP_AUTHORIZATION_CALLBACK_FAILED"
| "MCP_PROTOCOL_INITIALIZE_FAILED"
| "MCP_TOOL_DISCOVERY_FAILED"
| "MCP_TOOL_EXECUTION_FAILED"
| "MCP_RESOURCE_DISCOVERY_FAILED"
| "MCP_RESOURCE_READ_FAILED"
| "MCP_SHUTDOWN_FAILED"
const errorCodeByPhase: Record<EnterpriseMcpOperationPhase, EnterpriseMcpErrorCode> = {
configuration: "MCP_CONFIGURATION_FAILED",
"requirements-discovery": "MCP_REQUIREMENTS_DISCOVERY_FAILED",
"connection-handshake": "MCP_CONNECTION_HANDSHAKE_FAILED",
"authorization-callback": "MCP_AUTHORIZATION_CALLBACK_FAILED",
"protocol-initialize": "MCP_PROTOCOL_INITIALIZE_FAILED",
"tool-discovery": "MCP_TOOL_DISCOVERY_FAILED",
"tool-execution": "MCP_TOOL_EXECUTION_FAILED",
"resource-discovery": "MCP_RESOURCE_DISCOVERY_FAILED",
"resource-read": "MCP_RESOURCE_READ_FAILED",
shutdown: "MCP_SHUTDOWN_FAILED",
}
const phaseLabel: Record<EnterpriseMcpOperationPhase, string> = {
configuration: "connection configuration",
"requirements-discovery": "MCP connection requirements discovery",
"connection-handshake": "MCP connection handshake",
"authorization-callback": "OAuth authorization callback",
"protocol-initialize": "MCP protocol negotiation",
"tool-discovery": "MCP tool discovery",
"tool-execution": "MCP tool execution",
"resource-discovery": "MCP resource discovery",
"resource-read": "MCP resource read",
shutdown: "MCP client shutdown",
}
const requestPhaseLabel: Record<EnterpriseMcpRequestPhase, string> = {
"endpoint-request": "the configured MCP endpoint",
"oauth-resource-discovery": "OAuth protected-resource discovery",
"oauth-server-discovery": "OAuth authorization-server discovery",
"oauth-client-registration": "OAuth client registration",
"oauth-token-exchange": "OAuth token exchange",
"oauth-token-refresh": "OAuth token refresh",
"mcp-discovery": "the MCP server/discover request",
"mcp-initialize": "the MCP initialize request",
"mcp-tool-discovery": "the MCP tools/list request",
"mcp-tool-execution": "the MCP tools/call request",
"mcp-resource-discovery": "the MCP resource catalog request",
"mcp-resource-read": "the MCP resources/read request",
"unknown-request": "an MCP provider request",
}
export class EnterpriseMcpClientError extends Error {
readonly code: EnterpriseMcpErrorCode
readonly operationPhase: EnterpriseMcpOperationPhase
readonly requestPhase: EnterpriseMcpRequestPhase | null
constructor(input: {
operationPhase: EnterpriseMcpOperationPhase
requestPhase: EnterpriseMcpRequestPhase | null
cause: unknown
}) {
const request = input.requestPhase ? ` while requesting ${requestPhaseLabel[input.requestPhase]}` : ""
super(`Enterprise MCP failed during ${phaseLabel[input.operationPhase]}${request}.`, { cause: input.cause })
this.name = "EnterpriseMcpClientError"
this.code = errorCodeByPhase[input.operationPhase]
this.operationPhase = input.operationPhase
this.requestPhase = input.requestPhase
}
}
/**
* Marks a lifecycle abort as ours on the `data` of an MCP error. The SDK
* rethrows an `SdkError` untouched but collapses any other abort reason into
* `String(reason)` on a RequestTimeout, leaving downstream diagnostics unable
* to tell an OpenWork deadline apart from a provider-declared failure.
*/
export const ENTERPRISE_MCP_LIFECYCLE_DEADLINE_DATA_KEY = "enterpriseMcpLifecycleDeadline"
export class EnterpriseMcpLifecycleDeadlineError extends SdkError {
readonly operationPhase: EnterpriseMcpOperationPhase
constructor(operationPhase: EnterpriseMcpOperationPhase) {
super(SdkErrorCode.RequestTimeout, `Enterprise MCP ${operationPhase} exceeded its lifecycle deadline.`, {
[ENTERPRISE_MCP_LIFECYCLE_DEADLINE_DATA_KEY]: true,
operationPhase,
})
this.name = "EnterpriseMcpLifecycleDeadlineError"
this.operationPhase = operationPhase
}
}
/** Walks an error chain for the deadline marker set by this client. */
export function isEnterpriseMcpLifecycleDeadline(value: unknown): boolean {
let current: unknown = value
for (let depth = 0; depth < 5 && current; depth += 1) {
if (current instanceof EnterpriseMcpLifecycleDeadlineError) return true
if (typeof current === "object" && current !== null && "data" in current) {
const data: unknown = current.data
if (
typeof data === "object" && data !== null
&& ENTERPRISE_MCP_LIFECYCLE_DEADLINE_DATA_KEY in data
&& data[ENTERPRISE_MCP_LIFECYCLE_DEADLINE_DATA_KEY] === true
) {
return true
}
}
current = typeof current === "object" && current !== null && "cause" in current ? current.cause : undefined
}
return false
}
export type EnterpriseMcpOAuthContractErrorCode =
| "MCP_OAUTH_AUTHORIZATION_ID_REQUIRED"
| "MCP_OAUTH_AUTHORIZATION_MISSING"
| "MCP_OAUTH_AUTHORIZATION_EXPIRED"
| "MCP_OAUTH_AUTHORIZATION_CLIENT_CHANGED"
| "MCP_OAUTH_CLIENT_EXPIRED"
| "MCP_OAUTH_CREDENTIAL_EXPIRED"
| "MCP_OAUTH_CREDENTIAL_CHANGED"
| "MCP_OAUTH_CONFIGURATION_CHANGED"
| "MCP_OAUTH_CONFIGURATION_REQUIRED"
| "MCP_OAUTH_ISSUER_MISMATCH"
| "MCP_OAUTH_PERSISTENCE_INVALID"
| "MCP_LIFECYCLE_DEADLINE"
/** Safe, stable failures for application-owned OAuth persistence invariants. */
export class EnterpriseMcpOAuthContractError extends Error {
readonly code: EnterpriseMcpOAuthContractErrorCode
constructor(code: EnterpriseMcpOAuthContractErrorCode, message: string) {
super(message)
this.name = "EnterpriseMcpOAuthContractError"
this.code = code
}
}
export class EnterpriseMcpToolResultError extends Error {
readonly code = "MCP_TOOL_REPORTED_ERROR"
readonly providerSignal: Record<string, unknown> | undefined
constructor(result?: unknown) {
super("The MCP provider completed the request but reported that the tool operation failed.")
this.name = "EnterpriseMcpToolResultError"
const structuredContent = typeof result === "object" && result !== null && "structuredContent" in result
&& typeof result.structuredContent === "object" && result.structuredContent !== null
? result.structuredContent
: null
const content = typeof result === "object" && result !== null && "content" in result && Array.isArray(result.content)
? result.content
: []
const hasStandardInputValidationError = content.some((item) => {
if (typeof item !== "object" || item === null || !("type" in item) || item.type !== "text" || !("text" in item) || typeof item.text !== "string") {
return false
}
return /^Input validation error:\s*Invalid arguments for tool\b/i.test(item.text)
|| /^Invalid (?:tool )?(?:arguments|params)\b/i.test(item.text)
})
const providerStatus = structuredContent && "providerStatus" in structuredContent && typeof structuredContent.providerStatus === "number"
? structuredContent.providerStatus
: undefined
const category = structuredContent && "category" in structuredContent && typeof structuredContent.category === "string"
? structuredContent.category
: hasStandardInputValidationError
? "invalid_arguments"
: undefined
const requestId = structuredContent && "requestId" in structuredContent && typeof structuredContent.requestId === "string"
? structuredContent.requestId
: undefined
if (providerStatus === undefined && category === undefined && requestId === undefined) return
this.providerSignal = {
...(providerStatus !== undefined ? { providerStatus } : {}),
...(category !== undefined ? { category } : {}),
...(requestId !== undefined ? { requestId } : {}),
}
}
}
export type EnterpriseMcpToolInputErrorCode =
| "MCP_TOOL_ARGUMENT_SIZE_LIMIT"
| "MCP_TOOL_ARGUMENT_DEPTH_LIMIT"
| "MCP_TOOL_ARGUMENT_CYCLE"
| "MCP_TOOL_ARGUMENT_INVALID_JSON"
export class EnterpriseMcpToolInputError extends Error {
readonly code: EnterpriseMcpToolInputErrorCode
constructor(code: EnterpriseMcpToolInputErrorCode) {
super("The MCP tool arguments do not satisfy the bounded JSON input contract.")
this.name = "EnterpriseMcpToolInputError"
this.code = code
}
}
export type EnterpriseMcpCatalogErrorCode =
| "MCP_CATALOG_CURSOR_LOOP"
| "MCP_CATALOG_PAGE_LIMIT"
| "MCP_CATALOG_ITEM_LIMIT"
| "MCP_CATALOG_DUPLICATE_TOOL"
| "MCP_CATALOG_DUPLICATE_RESOURCE"
| "MCP_CATALOG_TOOL_NAME_LIMIT"
| "MCP_CATALOG_TOOL_DESCRIPTION_LIMIT"
| "MCP_CATALOG_TOOL_TITLE_LIMIT"
| "MCP_CATALOG_SCHEMA_SIZE_LIMIT"
| "MCP_CATALOG_SCHEMA_DEPTH_LIMIT"
| "MCP_CATALOG_SCHEMA_CYCLE"
| "MCP_CATALOG_CURSOR_SIZE_LIMIT"
| "MCP_CATALOG_BYTE_LIMIT"
| "MCP_RESOURCE_URI_LIMIT"
| "MCP_RESOURCE_DESCRIPTOR_LIMIT"
| "MCP_RESOURCE_RESULT_LIMIT"
export class EnterpriseMcpCatalogError extends Error {
readonly code: EnterpriseMcpCatalogErrorCode
constructor(code: EnterpriseMcpCatalogErrorCode) {
super("The MCP catalog or resource exceeded an enterprise client contract limit.")
this.name = "EnterpriseMcpCatalogError"
this.code = code
}
}
@@ -0,0 +1,8 @@
export * from "./contracts.js"
export * from "./oauth-resource-alias.js"
export * from "./authorization-response.js"
export * from "./enterprise-mcp-client.js"
export * from "./errors.js"
export * from "./requirements-discovery.js"
export * from "./resource-catalog.js"
export * from "./token-response-compat.js"
@@ -0,0 +1,42 @@
import type { OAuthDiscoveryState } from "@modelcontextprotocol/client"
import { isEquivalentOAuthDiscoveryAlias } from "./oauth-resource-alias.js"
type OAuthDiscoveryBindingState = Pick<OAuthDiscoveryState, "authorizationServerUrl"> & {
authorizationServerMetadata?: { issuer?: string }
resourceMetadata?: { resource?: string; authorization_servers?: string[] }
}
function isResourceScopedDiscoveryAlias(state: OAuthDiscoveryBindingState, expectedIssuer: string): boolean {
const advertisedIssuers = state.resourceMetadata?.authorization_servers
return state.authorizationServerUrl !== expectedIssuer
&& isEquivalentOAuthDiscoveryAlias(state.authorizationServerMetadata?.issuer, expectedIssuer)
&& isEquivalentOAuthDiscoveryAlias(state.resourceMetadata?.resource, state.authorizationServerUrl)
&& advertisedIssuers?.some((issuer) => isEquivalentOAuthDiscoveryAlias(issuer, state.authorizationServerUrl)) === true
}
function advertisesExpectedIssuerOrResourceAlias(
state: OAuthDiscoveryBindingState,
expectedIssuer: string,
): boolean {
const advertisedIssuers = state.resourceMetadata?.authorization_servers
if (advertisedIssuers === undefined) return true
return advertisedIssuers.some((issuer) => isEquivalentOAuthDiscoveryAlias(issuer, expectedIssuer))
|| advertisedIssuers.some((issuer) => isEquivalentOAuthDiscoveryAlias(issuer, state.resourceMetadata?.resource))
}
/**
* Bind OAuth metadata to either its advertised issuer or the constrained
* resource-scoped discovery alias advertised by the protected resource.
* The canonical metadata issuer remains the issuer used for callbacks.
*/
export function isAuthorizationServerDiscoveryBound(
state: OAuthDiscoveryBindingState,
expectedIssuer: string,
): boolean {
const directBinding = isEquivalentOAuthDiscoveryAlias(state.authorizationServerUrl, expectedIssuer)
&& advertisesExpectedIssuerOrResourceAlias(state, expectedIssuer)
const discoveryBinding = directBinding || isResourceScopedDiscoveryAlias(state, expectedIssuer)
return discoveryBinding
&& (state.authorizationServerMetadata?.issuer === undefined
|| isEquivalentOAuthDiscoveryAlias(state.authorizationServerMetadata.issuer, expectedIssuer))
}
@@ -0,0 +1,516 @@
import { OAuthClientInformationFullSchema, OAuthClientInformationSchema, OAuthTokensSchema } from "@modelcontextprotocol/core"
import { discoverAuthorizationServerMetadata, IssuerMismatchError } from "@modelcontextprotocol/client"
import type {
AuthorizationServerMetadata,
OAuthClientInformationContext,
OAuthClientProvider,
OAuthDiscoveryState,
StoredOAuthClientInformation,
StoredOAuthTokens,
} from "@modelcontextprotocol/client"
import { isEquivalentOAuthDiscoveryAlias } from "./oauth-resource-alias.js"
import type {
EnterpriseMcpClock,
EnterpriseMcpLifecycle,
EnterpriseMcpOAuthAuthorizationHandle,
EnterpriseMcpOAuthClientRegistration,
EnterpriseMcpOAuthCredential,
EnterpriseMcpOAuthConfiguration,
EnterpriseMcpFetch,
EnterpriseMcpOAuthPersistence,
EnterpriseMcpPersistenceContext,
} from "./contracts.js"
import { EnterpriseMcpOAuthContractError } from "./errors.js"
import { isAuthorizationServerDiscoveryBound } from "./oauth-discovery-binding.js"
type OAuthFlowContext =
| { kind: "connect"; authorizationId?: string }
| { kind: "callback"; authorizationId: string }
| { kind: "runtime" }
type VerifiedOAuthDiscoveryState = OAuthDiscoveryState & {
openworkMetadataVerification?: {
version: 1
issuer: string
}
}
const oauthClientInformationMixedSchema = OAuthClientInformationFullSchema.or(OAuthClientInformationSchema)
function assertFiniteEpoch(value: number, field: string): number {
if (!Number.isFinite(value) || value < 0) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_PERSISTENCE_INVALID",
`The OAuth persistence adapter returned an invalid ${field}.`,
)
}
return value
}
function clientExpiration(clientInformation: StoredOAuthClientInformation): number | undefined {
const parsed = OAuthClientInformationFullSchema.safeParse(clientInformation)
const seconds = parsed.success ? parsed.data.client_secret_expires_at : undefined
if (seconds === undefined || seconds === 0) return undefined
return assertFiniteEpoch(seconds * 1_000, "client expiration")
}
function tokenExpiration(tokens: StoredOAuthTokens, now: number): number | undefined {
if (tokens.expires_in === undefined) return undefined
if (!Number.isFinite(tokens.expires_in) || tokens.expires_in < 0) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_PERSISTENCE_INVALID",
"The OAuth provider returned an invalid access-token lifetime.",
)
}
return assertFiniteEpoch(now + tokens.expires_in * 1_000, "token expiration")
}
export class EnterpriseMcpOAuthProvider implements OAuthClientProvider {
private readonly redirectUri: string
private readonly connectionId: string
private readonly persistence: EnterpriseMcpOAuthPersistence
private readonly flow: OAuthFlowContext
private readonly clientName: string
private readonly clock: EnterpriseMcpClock
private readonly lifecycle: EnterpriseMcpLifecycle
private readonly authorizationTransactionTtlMs: number
private readonly expirationSkewMs: number
private readonly applicationType: EnterpriseMcpOAuthConfiguration["applicationType"]
private readonly authorizationServerIssuer: string | undefined
private readonly requestedScopes: string[]
private readonly fetch: EnterpriseMcpFetch
readonly clientMetadataUrl: string | undefined
private loadedClient: EnterpriseMcpOAuthClientRegistration | undefined
private loadedCredential: EnterpriseMcpOAuthCredential | undefined
private loadedDiscovery: OAuthDiscoveryState | undefined
private verifiedAuthorizationServerMetadata: AuthorizationServerMetadata | undefined
private authorizationHandle: EnterpriseMcpOAuthAuthorizationHandle | undefined
authorizeUrl: string | null = null
constructor(input: {
redirectUri: string
connectionId: string
persistence: EnterpriseMcpOAuthPersistence
flow: OAuthFlowContext
clientName: string
clock: EnterpriseMcpClock
lifecycle: EnterpriseMcpLifecycle
authorizationTransactionTtlMs: number
expirationSkewMs: number
fetch: EnterpriseMcpFetch
oauthConfiguration?: EnterpriseMcpOAuthConfiguration
}) {
this.redirectUri = input.redirectUri
this.connectionId = input.connectionId
this.persistence = input.persistence
this.flow = input.flow
this.clientName = input.clientName
this.clock = input.clock
this.lifecycle = input.lifecycle
this.authorizationTransactionTtlMs = input.authorizationTransactionTtlMs
this.expirationSkewMs = input.expirationSkewMs
this.applicationType = input.oauthConfiguration?.applicationType ?? "web"
this.clientMetadataUrl = input.oauthConfiguration?.clientMetadataUrl
this.authorizationServerIssuer = input.oauthConfiguration?.authorizationServerIssuer
this.requestedScopes = [...new Set(input.oauthConfiguration?.requestedScopes ?? [])]
this.fetch = input.fetch
}
private context(): EnterpriseMcpPersistenceContext {
const now = this.clock.now()
if (this.lifecycle.signal.aborted || now >= this.lifecycle.expiresAt) {
throw new EnterpriseMcpOAuthContractError(
"MCP_LIFECYCLE_DEADLINE",
"The enterprise MCP lifecycle expired before OAuth persistence could continue.",
)
}
return {
connectionId: this.connectionId,
commitExpiresAt: this.lifecycle.expiresAt,
signal: this.lifecycle.signal,
}
}
get redirectUrl(): string {
return this.redirectUri
}
state(): string {
if (this.flow.kind !== "connect" || !this.flow.authorizationId) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_AUTHORIZATION_ID_REQUIRED",
"A signed authorization transaction id is required before starting OAuth.",
)
}
return this.flow.authorizationId
}
get clientMetadata() {
const scope = this.requestedScopes.join(" ")
return {
redirect_uris: [this.redirectUri],
client_name: this.clientName,
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
token_endpoint_auth_method: "none",
application_type: this.applicationType,
...(scope ? { scope } : {}),
}
}
private assertDiscoveryBinding(state: OAuthDiscoveryState): void {
const selectedIssuer = this.authorizationServerIssuer
if (!selectedIssuer) {
if ((state.resourceMetadata?.authorization_servers?.length ?? 0) > 1) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_CONFIGURATION_REQUIRED",
"This MCP resource advertises multiple authorization servers; an administrator must select one before connecting.",
)
}
return
}
if (!isAuthorizationServerDiscoveryBound(state, selectedIssuer)) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The OAuth authorization server does not match the issuer selected for this MCP connection.",
)
}
}
private expectedCredentialIssuer(context?: OAuthClientInformationContext): string | undefined {
const boundIssuer = this.authorizationServerIssuer
?? this.loadedDiscovery?.authorizationServerMetadata?.issuer
?? this.loadedDiscovery?.authorizationServerUrl
if (context?.issuer && boundIssuer && !isEquivalentOAuthDiscoveryAlias(context.issuer, boundIssuer)) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The OAuth credential context does not match the selected authorization server issuer.",
)
}
return boundIssuer ?? context?.issuer
}
private assertStoredIssuer(issuer: string | undefined, expectedIssuer: string | undefined): void {
if (issuer === undefined || expectedIssuer === undefined || isEquivalentOAuthDiscoveryAlias(issuer, expectedIssuer)) return
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The stored OAuth credential does not match the selected authorization server issuer.",
)
}
private storedClientInformation(
clientInformation: StoredOAuthClientInformation,
context?: OAuthClientInformationContext,
): StoredOAuthClientInformation {
const expectedIssuer = this.expectedCredentialIssuer(context)
this.assertStoredIssuer(clientInformation.issuer, expectedIssuer)
const validated = oauthClientInformationMixedSchema.parse(clientInformation)
const issuer = clientInformation.issuer ?? expectedIssuer
return { ...validated, ...(issuer ? { issuer } : {}) }
}
private storedTokens(tokens: StoredOAuthTokens, context?: OAuthClientInformationContext): StoredOAuthTokens {
const expectedIssuer = this.expectedCredentialIssuer(context)
this.assertStoredIssuer(tokens.issuer, expectedIssuer)
const validated = OAuthTokensSchema.parse(tokens)
const issuer = tokens.issuer ?? expectedIssuer
return { ...validated, ...(issuer ? { issuer } : {}) }
}
private async canonicalAuthorizationServerMetadata(): Promise<AuthorizationServerMetadata | undefined> {
const selectedIssuer = this.authorizationServerIssuer
if (!selectedIssuer) return undefined
if (isEquivalentOAuthDiscoveryAlias(this.verifiedAuthorizationServerMetadata?.issuer, selectedIssuer)) {
return this.verifiedAuthorizationServerMetadata
}
let metadata: AuthorizationServerMetadata | undefined
try {
metadata = await discoverAuthorizationServerMetadata(selectedIssuer, { fetchFn: this.fetch })
} catch (error) {
if (error instanceof IssuerMismatchError) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_ISSUER_MISMATCH",
"The selected OAuth issuer could not be verified against its canonical metadata.",
)
}
throw error
}
if (!metadata) {
throw new Error(`No OAuth metadata was found for the selected issuer ${selectedIssuer}.`)
}
this.verifiedAuthorizationServerMetadata = metadata
return metadata
}
private hasCurrentMetadataVerification(state: OAuthDiscoveryState, selectedIssuer: string): boolean {
const verification = (state as VerifiedOAuthDiscoveryState).openworkMetadataVerification
// The stamp records the canonical metadata issuer; the selected issuer may
// be its equivalent root trailing-slash alias (RFC 8414's one tolerance).
return verification?.version === 1
&& isEquivalentOAuthDiscoveryAlias(verification.issuer, selectedIssuer)
&& state.authorizationServerUrl === verification.issuer
&& state.authorizationServerMetadata?.issuer === verification.issuer
}
private async normalizeDiscoveryState(state: OAuthDiscoveryState | undefined): Promise<VerifiedOAuthDiscoveryState | undefined> {
const selectedIssuer = this.authorizationServerIssuer
if (!selectedIssuer) return state
if (state) {
this.assertDiscoveryBinding(state)
if (this.hasCurrentMetadataVerification(state, selectedIssuer)) {
this.verifiedAuthorizationServerMetadata = state.authorizationServerMetadata
return state
}
}
const metadata = await this.canonicalAuthorizationServerMetadata()
if (!metadata) return state
const normalized: VerifiedOAuthDiscoveryState = {
...state,
authorizationServerUrl: metadata.issuer,
authorizationServerMetadata: metadata,
openworkMetadataVerification: {
version: 1,
issuer: metadata.issuer,
},
}
this.assertDiscoveryBinding(normalized)
return normalized
}
async discoveryState(): Promise<OAuthDiscoveryState | undefined> {
const persistedState = await this.persistence.discovery?.load(this.context())
const state = await this.normalizeDiscoveryState(persistedState)
if (state) {
this.assertDiscoveryBinding(state)
// normalizeDiscoveryState returns the same object when nothing needed
// verification or repair; only a rebuilt state warrants a re-save.
if (persistedState && state !== persistedState) {
await this.persistence.discovery?.save({ context: this.context(), state })
}
this.loadedDiscovery = state
}
return state
}
async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {
let normalizedState: OAuthDiscoveryState | undefined
try {
normalizedState = await this.normalizeDiscoveryState(state)
if (!normalizedState) throw new Error("OAuth discovery state was unavailable.")
this.assertDiscoveryBinding(normalizedState)
} catch (error) {
// Only a proven binding violation invalidates persisted discovery and
// flags issuer review; a transient metadata outage must stay retryable.
if (error instanceof EnterpriseMcpOAuthContractError) {
await this.persistence.discovery?.invalidate({
context: this.context(),
reason: "issuer-mismatch",
})
}
throw error
}
await this.persistence.discovery?.save({ context: this.context(), state: normalizedState })
this.loadedDiscovery = normalizedState
}
async clientInformation(context?: OAuthClientInformationContext): Promise<StoredOAuthClientInformation | undefined> {
const record = await this.persistence.clientRegistrations.load(this.context())
if (!record) {
this.loadedClient = undefined
const metadata = this.loadedDiscovery?.authorizationServerMetadata
const canUseClientMetadata = metadata?.client_id_metadata_document_supported === true && Boolean(this.clientMetadataUrl)
if (metadata && !canUseClientMetadata && !metadata.registration_endpoint) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_CONFIGURATION_REQUIRED",
"The authorization server does not advertise client metadata documents or dynamic registration; an administrator must supply a pre-registered OAuth client.",
)
}
return undefined
}
const clientInformation = this.storedClientInformation(record.clientInformation, context)
if (!record.revision.trim()) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_PERSISTENCE_INVALID",
"The OAuth client registration is missing its persistence revision.",
)
}
if (record.expiresAt !== undefined) {
assertFiniteEpoch(record.expiresAt, "client expiration")
if (record.expiresAt <= this.clock.now() + this.expirationSkewMs) {
await this.persistence.clientRegistrations.invalidate({ context: this.context(), reason: "expired" })
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_CLIENT_EXPIRED",
"The OAuth client registration or client secret has expired and must be renewed.",
)
}
}
this.loadedClient = record
return clientInformation
}
async saveClientInformation(
clientInformation: StoredOAuthClientInformation,
context?: OAuthClientInformationContext,
): Promise<void> {
const validated = this.storedClientInformation(clientInformation, context)
const source = this.clientMetadataUrl === validated.client_id ? "client-metadata" : "dynamic"
const saved = await this.persistence.clientRegistrations.save({
context: this.context(),
clientInformation: validated,
redirectUri: this.redirectUri,
expiresAt: clientExpiration(validated),
source,
})
if (saved.clientInformation.client_id !== validated.client_id) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_AUTHORIZATION_CLIENT_CHANGED",
"A different OAuth client registration won a concurrent registration attempt; retry the connection.",
)
}
this.loadedClient = saved
}
async tokens(context?: OAuthClientInformationContext): Promise<StoredOAuthTokens | undefined> {
const record = await this.persistence.credentials.load(this.context())
if (!record) {
this.loadedCredential = undefined
return undefined
}
const tokens = this.storedTokens(record.tokens, context)
if (!record.revision.trim()) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_PERSISTENCE_INVALID",
"The OAuth credential is missing its persistence revision.",
)
}
if (record.expiresAt !== undefined) {
assertFiniteEpoch(record.expiresAt, "token expiration")
if (record.expiresAt <= this.clock.now() + this.expirationSkewMs && !tokens.refresh_token) {
await this.persistence.credentials.invalidate({ context: this.context(), reason: "expired" })
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_CREDENTIAL_EXPIRED",
"The OAuth access token has expired and no refresh token is available.",
)
}
}
this.loadedCredential = { ...record, tokens }
return tokens
}
async saveTokens(tokens: StoredOAuthTokens, context?: OAuthClientInformationContext): Promise<void> {
const validated = this.storedTokens(tokens, context)
const source = this.authorizationHandle ? "authorization-code" : "refresh"
const existing = source === "refresh"
? (this.loadedCredential ?? await this.persistence.credentials.load(this.context()))
: undefined
const merged = source === "refresh" && !validated.refresh_token && existing?.tokens.refresh_token
? { ...validated, refresh_token: existing.tokens.refresh_token }
: validated
await this.persistence.credentials.save({
context: this.context(),
tokens: merged,
expiresAt: tokenExpiration(merged, this.clock.now()),
source,
authorization: this.authorizationHandle,
clientRegistrationRevision: this.loadedClient?.revision,
expectedCredentialRevision: source === "refresh" ? existing?.revision : undefined,
})
this.loadedCredential = undefined
}
redirectToAuthorization(authorizationUrl: URL): void {
this.authorizeUrl = authorizationUrl.toString()
}
async saveCodeVerifier(codeVerifier: string): Promise<void> {
if (this.flow.kind !== "connect" || !this.flow.authorizationId) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_AUTHORIZATION_ID_REQUIRED",
"A signed authorization transaction id is required before PKCE can be persisted.",
)
}
const expiresAt = this.clock.now() + this.authorizationTransactionTtlMs
await this.persistence.authorizations.begin({
context: this.context(),
id: this.flow.authorizationId,
codeVerifier,
expiresAt,
clientRegistrationRevision: this.loadedClient?.revision,
})
}
async codeVerifier(): Promise<string> {
if (this.flow.kind !== "callback") {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_AUTHORIZATION_ID_REQUIRED",
"The OAuth callback is missing its signed authorization transaction id.",
)
}
const transaction = await this.persistence.authorizations.load({
context: this.context(),
id: this.flow.authorizationId,
})
if (!transaction) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_AUTHORIZATION_MISSING",
"The OAuth authorization transaction is missing or was already consumed.",
)
}
if (transaction.handle.expiresAt <= this.clock.now() + this.expirationSkewMs) {
await this.persistence.authorizations.invalidate({
context: this.context(),
id: this.flow.authorizationId,
reason: "expired",
})
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_AUTHORIZATION_EXPIRED",
"The OAuth authorization transaction has expired; start the connection again.",
)
}
const clientRevision = this.loadedClient?.revision
if (
transaction.handle.clientRegistrationRevision !== undefined
&& transaction.handle.clientRegistrationRevision !== clientRevision
) {
throw new EnterpriseMcpOAuthContractError(
"MCP_OAUTH_AUTHORIZATION_CLIENT_CHANGED",
"The OAuth client registration changed after authorization started.",
)
}
this.authorizationHandle = transaction.handle
return transaction.codeVerifier
}
async invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void> {
if (scope === "all" || scope === "client") {
await this.persistence.clientRegistrations.invalidate({
context: this.context(),
reason: "provider-rejected",
})
}
if (scope === "all" || scope === "tokens") {
await this.persistence.credentials.invalidate({
context: this.context(),
reason: "provider-rejected",
})
}
if ((scope === "all" || scope === "verifier") && this.flow.kind !== "runtime") {
const id = this.flow.authorizationId
if (id) {
await this.persistence.authorizations.invalidate({
context: this.context(),
id,
reason: "provider-rejected",
})
}
}
if (scope === "all" || scope === "discovery") {
await this.persistence.discovery?.invalidate({
context: this.context(),
reason: "provider-rejected",
})
}
}
}
@@ -0,0 +1,25 @@
/**
* OAuth discovery documents may advertise the same HTTP(S) root URL with or
* without its trailing slash. Exact non-root identifiers remain valid, but
* non-root paths, query strings, and fragments are never normalized.
*
* This is only for binding discovery metadata. Authorization-response issuer
* checks must continue comparing the canonical metadata issuer exactly.
*/
export function isEquivalentOAuthDiscoveryAlias(left: string | undefined, right: string | undefined): boolean {
if (!left || !right) return false
if (left === right) return true
try {
const leftUrl = new URL(left)
const rightUrl = new URL(right)
const supportedProtocol = (protocol: string) => protocol === "http:" || protocol === "https:"
if (!supportedProtocol(leftUrl.protocol) || !supportedProtocol(rightUrl.protocol)) return false
if (leftUrl.search || rightUrl.search || leftUrl.hash || rightUrl.hash) return false
return leftUrl.origin === rightUrl.origin
&& leftUrl.pathname === "/"
&& rightUrl.pathname === "/"
} catch {
return false
}
}
@@ -0,0 +1,182 @@
import { z } from "zod"
import type {
EnterpriseMcpDiagnosticSink,
EnterpriseMcpClock,
EnterpriseMcpFetch,
EnterpriseMcpOperationPhase,
EnterpriseMcpRequestPhase,
} from "./contracts.js"
import { boundedRedactedResponseBodyExcerpt } from "./response-body-excerpt.js"
const jsonRpcRequestSchema = z.object({
method: z.string(),
}).passthrough()
function requestBodyText(body: BodyInit | null | undefined): string | null {
if (typeof body === "string") return body
if (body instanceof URLSearchParams) return body.toString()
return null
}
function bodyRequestPhase(body: BodyInit | null | undefined): EnterpriseMcpRequestPhase | null {
const text = requestBodyText(body)
if (!text) return null
const form = new URLSearchParams(text)
const grantType = form.get("grant_type")
if (grantType === "authorization_code") return "oauth-token-exchange"
if (grantType === "refresh_token") return "oauth-token-refresh"
try {
const parsed: unknown = JSON.parse(text)
const request = jsonRpcRequestSchema.safeParse(parsed)
if (!request.success) {
if (typeof parsed === "object" && parsed !== null && "redirect_uris" in parsed) {
return "oauth-client-registration"
}
return null
}
if (request.data.method === "server/discover") return "mcp-discovery"
if (request.data.method === "initialize") return "mcp-initialize"
if (request.data.method === "tools/list") return "mcp-tool-discovery"
if (request.data.method === "tools/call") return "mcp-tool-execution"
if (request.data.method === "resources/list" || request.data.method === "resources/templates/list") return "mcp-resource-discovery"
if (request.data.method === "resources/read") return "mcp-resource-read"
} catch {
return null
}
return null
}
function isMcpRequestPhase(phase: EnterpriseMcpRequestPhase): boolean {
return phase === "endpoint-request"
|| phase === "mcp-discovery"
|| phase === "mcp-initialize"
|| phase === "mcp-tool-discovery"
|| phase === "mcp-tool-execution"
|| phase === "mcp-resource-discovery"
|| phase === "mcp-resource-read"
}
export function classifyEnterpriseMcpRequest(url: URL, init?: RequestInit): EnterpriseMcpRequestPhase {
const bodyPhase = bodyRequestPhase(init?.body)
if (bodyPhase) return bodyPhase
if (url.pathname.includes("/.well-known/oauth-protected-resource")) {
return "oauth-resource-discovery"
}
if (url.pathname.includes("/.well-known/oauth-authorization-server") || url.pathname.includes("/.well-known/openid-configuration")) {
return "oauth-server-discovery"
}
if (init?.method === "POST" && url.pathname.includes("register")) {
return "oauth-client-registration"
}
return "endpoint-request"
}
export type EnterpriseMcpRequestObserver = {
fetch: EnterpriseMcpFetch
lastRequestPhase(): EnterpriseMcpRequestPhase | null
lastFailedRequestPhase(): EnterpriseMcpRequestPhase | null
lastRequestFailure(): {
requestPhase: EnterpriseMcpRequestPhase
httpStatus?: number
bearerChallenge: boolean
insufficientScope: boolean
invalidToken: boolean
} | null
}
export function createEnterpriseMcpRequestObserver(input: {
connectionId: string
operationPhase: EnterpriseMcpOperationPhase
fetch: EnterpriseMcpFetch
diagnosticSink?: EnterpriseMcpDiagnosticSink
signal: AbortSignal
clock: EnterpriseMcpClock
}): EnterpriseMcpRequestObserver {
let lastRequestPhase: EnterpriseMcpRequestPhase | null = null
let lastFailedRequestPhase: EnterpriseMcpRequestPhase | null = null
let lastRequestFailure: ReturnType<EnterpriseMcpRequestObserver["lastRequestFailure"]> = null
const emitDiagnostic: EnterpriseMcpDiagnosticSink = (event) => {
try {
input.diagnosticSink?.(event)
} catch {
// Diagnostics must never change the request outcome they observe.
}
}
return {
lastRequestPhase: () => lastRequestPhase,
lastFailedRequestPhase: () => lastFailedRequestPhase,
lastRequestFailure: () => lastRequestFailure,
fetch: async (rawUrl, init) => {
const url = rawUrl instanceof URL ? rawUrl : new URL(rawUrl)
const requestPhase = classifyEnterpriseMcpRequest(url, init)
lastRequestPhase = requestPhase
const startedAt = input.clock.now()
emitDiagnostic({
kind: "request",
connectionId: input.connectionId,
operationPhase: input.operationPhase,
requestPhase,
outcome: "started",
})
try {
const signal = init?.signal
? AbortSignal.any([init.signal, input.signal])
: input.signal
const response = await input.fetch(rawUrl, { ...init, signal })
if (!response.ok) {
lastFailedRequestPhase = requestPhase
const challenge = response.headers.get("www-authenticate")?.toLowerCase() ?? ""
lastRequestFailure = {
requestPhase,
httpStatus: response.status,
bearerChallenge: challenge.includes("bearer"),
insufficientScope: challenge.includes("insufficient_scope"),
invalidToken: challenge.includes("invalid_token"),
}
} else if (isMcpRequestPhase(requestPhase)) {
// A successful retry proves that a preceding challenge was
// recoverable. OAuth discovery/refresh requests deliberately do not
// erase the resource's last rejection before that retry completes.
lastRequestFailure = null
}
const responseBodyExcerpt = !response.ok && isMcpRequestPhase(requestPhase)
? await boundedRedactedResponseBodyExcerpt(response)
: undefined
emitDiagnostic({
kind: "request",
connectionId: input.connectionId,
operationPhase: input.operationPhase,
requestPhase,
outcome: response.ok ? "succeeded" : "failed",
durationMs: input.clock.now() - startedAt,
httpStatus: response.status,
...(responseBodyExcerpt ? { responseBodyExcerpt } : {}),
})
return response
} catch (error) {
lastFailedRequestPhase = requestPhase
lastRequestFailure = {
requestPhase,
bearerChallenge: false,
insufficientScope: false,
invalidToken: false,
}
emitDiagnostic({
kind: "request",
connectionId: input.connectionId,
operationPhase: input.operationPhase,
requestPhase,
outcome: "failed",
durationMs: input.clock.now() - startedAt,
})
throw error
}
},
}
}
@@ -0,0 +1,364 @@
import {
Client,
discoverAuthorizationServerMetadata,
discoverOAuthProtectedResourceMetadata,
extractWWWAuthenticateParams,
IssuerMismatchError,
StreamableHTTPClientTransport,
} from "@modelcontextprotocol/client"
import type { AuthorizationServerMetadata } from "@modelcontextprotocol/client"
import type {
DiscoverEnterpriseMcpConnectionRequirementsInput,
EnterpriseMcpAuthorizationServerRequirement,
EnterpriseMcpConnectionRequirements,
EnterpriseMcpFetch,
} from "./contracts.js"
import { isEquivalentOAuthDiscoveryAlias } from "./oauth-resource-alias.js"
const DEFAULT_TIMEOUT_MS = 15_000
const DEFAULT_MAX_AUTHORIZATION_SERVERS = 5
const DEFAULT_MAX_TOOLS = 100
const MAX_RESPONSE_BYTES = 1024 * 1024
const MAX_TOOL_PAGES = 5
/**
* Select a canonical issuer only when fresh requirements discovery proves
* that a stale configured value is either the same root issuer alias or the
* protected resource's own discovery alias. Ambiguous and partially invalid
* discovery results remain manual failures.
*/
export function selectRecoverableAuthorizationServerIssuer(input: {
selectedIssuer: string
requirements: Pick<EnterpriseMcpConnectionRequirements, "authentication" | "warnings">
}): string | undefined {
if (
input.requirements.authentication.kind !== "oauth"
|| input.requirements.authentication.authorizationServers.length !== 1
|| input.requirements.warnings.some((warning) => warning.code === "oauth_issuer_mismatch")
) return undefined
const canonicalIssuer = input.requirements.authentication.authorizationServers[0]?.issuer
if (!canonicalIssuer || canonicalIssuer === input.selectedIssuer) return undefined
if (isEquivalentOAuthDiscoveryAlias(input.selectedIssuer, canonicalIssuer)) return canonicalIssuer
return isEquivalentOAuthDiscoveryAlias(input.selectedIssuer, input.requirements.authentication.resource)
? canonicalIssuer
: undefined
}
function boundedResponse(response: Response): Response {
const advertisedLength = Number(response.headers.get("content-length"))
if (Number.isFinite(advertisedLength) && advertisedLength > MAX_RESPONSE_BYTES) {
void response.body?.cancel()
throw new Error("The MCP discovery response exceeded the 1 MiB limit.")
}
if (!response.body) return response
const reader = response.body.getReader()
let bytesRead = 0
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
const result = await reader.read()
if (result.done) {
controller.close()
return
}
bytesRead += result.value.byteLength
if (bytesRead > MAX_RESPONSE_BYTES) {
await reader.cancel()
controller.error(new Error("The MCP discovery response exceeded the 1 MiB limit."))
return
}
controller.enqueue(result.value)
},
async cancel(reason) {
await reader.cancel(reason)
},
})
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
})
}
function scopedFetch(input: {
fetch: EnterpriseMcpFetch
signal: AbortSignal
observe: (response: Response) => void
}): EnterpriseMcpFetch {
return async (url, init) => {
const signal = init?.signal
? AbortSignal.any([init.signal, input.signal])
: input.signal
const response = boundedResponse(await input.fetch(url, { ...init, signal }))
input.observe(response)
return response
}
}
function metadataRequirement(metadata: AuthorizationServerMetadata): EnterpriseMcpAuthorizationServerRequirement {
return {
issuer: metadata.issuer,
authorizationEndpoint: metadata.authorization_endpoint,
tokenEndpoint: metadata.token_endpoint,
registrationEndpoint: metadata.registration_endpoint,
clientIdMetadataDocumentSupported: metadata.client_id_metadata_document_supported === true,
scopesSupported: metadata.scopes_supported,
grantTypesSupported: metadata.grant_types_supported,
codeChallengeMethodsSupported: metadata.code_challenge_methods_supported,
tokenEndpointAuthMethodsSupported: metadata.token_endpoint_auth_methods_supported,
}
}
async function discoverBoundAuthorizationServerMetadata(input: {
advertisedIssuer: string
resource: string | undefined
fetch: EnterpriseMcpFetch
}): Promise<AuthorizationServerMetadata | null> {
let canonicalIssuer: string
try {
return await discoverAuthorizationServerMetadata(input.advertisedIssuer, { fetchFn: input.fetch }) ?? null
} catch (error) {
if (
!(error instanceof IssuerMismatchError)
|| !isEquivalentOAuthDiscoveryAlias(input.advertisedIssuer, input.resource)
|| typeof error.received !== "string"
|| !error.received
) throw error
canonicalIssuer = error.received
}
// A few providers advertise the protected resource as a discovery alias.
// The strict SDK mismatch exposes only the parsed issuer identifier. Treat
// that value as a pointer, independently rediscover it with RFC 8414 issuer
// validation enabled, and never consume endpoints from the alias document.
return await discoverAuthorizationServerMetadata(canonicalIssuer, {
fetchFn: input.fetch,
}) ?? null
}
function uniqueScopes(value: string | undefined): string[] {
if (!value) return []
return [...new Set(value.split(/\s+/).map((scope) => scope.trim()).filter(Boolean))]
}
function manualRequirements(input: {
authorizationServers: EnterpriseMcpAuthorizationServerRequirement[]
authenticationRequired: boolean
}): EnterpriseMcpConnectionRequirements["manualRequirements"] {
const requirements: EnterpriseMcpConnectionRequirements["manualRequirements"] = [
{
code: "provider_access",
label: "Provider access",
reason: "Provider roles, licenses, tenant access, and administrator consent are not described by MCP OAuth metadata.",
required: false,
},
{
code: "network_trust",
label: "Network trust",
reason: "Private routing, proxy, firewall, and private CA requirements must be confirmed in the Den deployment environment.",
required: false,
},
]
if (input.authorizationServers.length > 1) {
requirements.unshift({
code: "authorization_server_selection",
label: "Choose an authorization server",
reason: "The protected resource advertises more than one issuer, so an administrator must bind this connection to one.",
required: true,
})
}
if (
input.authenticationRequired
&& !input.authorizationServers.some((server) => server.clientIdMetadataDocumentSupported || server.registrationEndpoint)
) {
requirements.unshift({
code: "oauth_client_registration",
label: "Register an OAuth client",
reason: "The authorization server does not advertise client metadata documents or dynamic registration.",
required: true,
})
}
return requirements
}
export async function discoverConnectionRequirements(
input: DiscoverEnterpriseMcpConnectionRequirementsInput,
): Promise<EnterpriseMcpConnectionRequirements> {
const serverUrl = new URL(input.serverUrl)
if (serverUrl.protocol !== "http:" && serverUrl.protocol !== "https:") {
throw new Error("An enterprise MCP server URL must use HTTP or HTTPS.")
}
if (serverUrl.username || serverUrl.password || serverUrl.hash) {
throw new Error("An enterprise MCP server URL cannot contain credentials or a fragment.")
}
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(new Error("MCP requirements discovery timed out.")), input.timeoutMs ?? DEFAULT_TIMEOUT_MS)
let lastStatus: number | undefined
let resourceMetadataUrl: URL | undefined
let challengeScope: string | undefined
const fetch = scopedFetch({
fetch: input.fetch,
signal: controller.signal,
observe: (response) => {
lastStatus = response.status
if (response.status !== 401 && response.status !== 403) return
const challenge = extractWWWAuthenticateParams(response)
resourceMetadataUrl = challenge.resourceMetadataUrl ?? resourceMetadataUrl
challengeScope = challenge.scope ?? challengeScope
},
})
const warnings: EnterpriseMcpConnectionRequirements["warnings"] = []
const tools: NonNullable<EnterpriseMcpConnectionRequirements["tools"]["items"]> = []
let initialize: EnterpriseMcpConnectionRequirements["server"]["initialize"] = "failed"
let protocolEra: EnterpriseMcpConnectionRequirements["server"]["protocolEra"]
let protocolVersion: string | undefined
let authenticationRequired = false
let client: Client | undefined
try {
client = new Client(
{ name: "OpenWork requirements discovery", version: "1.0.0" },
{ capabilities: {}, versionNegotiation: { mode: "auto" } },
)
const transport = new StreamableHTTPClientTransport(serverUrl, { fetch })
await client.connect(transport, { signal: controller.signal })
initialize = "succeeded"
protocolEra = client.getProtocolEra()
protocolVersion = client.getNegotiatedProtocolVersion()
let cursor: string | undefined
const maxTools = input.maxTools ?? DEFAULT_MAX_TOOLS
for (let page = 0; page < MAX_TOOL_PAGES && tools.length < maxTools; page += 1) {
const result = await client.listTools(cursor ? { cursor } : undefined, { signal: controller.signal })
for (const tool of result.tools) {
if (tools.length >= maxTools) break
tools.push({
name: tool.name,
readOnlyHint: tool.annotations?.readOnlyHint,
destructiveHint: tool.annotations?.destructiveHint,
openWorldHint: tool.annotations?.openWorldHint,
})
}
cursor = result.nextCursor
if (!cursor) break
}
} catch (error) {
authenticationRequired = lastStatus === 401 || lastStatus === 403
initialize = authenticationRequired ? "authentication_required" : "failed"
if (!authenticationRequired) {
warnings.push({
code: lastStatus ? `mcp_http_${lastStatus}` : "mcp_unreachable",
message: error instanceof Error ? error.message : "The MCP endpoint could not be reached.",
})
}
} finally {
try {
await client?.close()
} catch {
// Discovery results remain useful even when best-effort transport cleanup fails.
}
}
let resourceMetadata: Awaited<ReturnType<typeof discoverOAuthProtectedResourceMetadata>> | undefined
try {
resourceMetadata = await discoverOAuthProtectedResourceMetadata(
serverUrl,
resourceMetadataUrl ? { resourceMetadataUrl } : undefined,
fetch,
)
} catch (error) {
if (authenticationRequired) {
warnings.push({
code: "oauth_resource_metadata_unavailable",
message: error instanceof Error ? error.message : "Protected-resource metadata could not be discovered.",
})
}
}
const advertisedIssuers = (resourceMetadata?.authorization_servers ?? [])
.slice(0, input.maxAuthorizationServers ?? DEFAULT_MAX_AUTHORIZATION_SERVERS)
const authorizationServers: EnterpriseMcpAuthorizationServerRequirement[] = []
for (const issuer of advertisedIssuers) {
try {
const metadata = await discoverBoundAuthorizationServerMetadata({
advertisedIssuer: issuer,
resource: resourceMetadata?.resource,
fetch,
})
if (!metadata) {
warnings.push({ code: "oauth_server_metadata_unavailable", message: `No OAuth metadata was found for issuer ${issuer}.` })
continue
}
authorizationServers.push(metadataRequirement(metadata))
} catch (error) {
warnings.push({
code: error instanceof IssuerMismatchError ? "oauth_issuer_mismatch" : "oauth_server_metadata_unavailable",
message: error instanceof Error ? error.message : `OAuth metadata could not be loaded for issuer ${issuer}.`,
})
}
}
const requiredScopes = uniqueScopes(challengeScope)
const refreshSupported = authorizationServers.some((server) => server.grantTypesSupported?.includes("refresh_token"))
const offlineAccessSupported = authorizationServers.some((server) => server.scopesSupported?.includes("offline_access"))
const recommendedScopes = requiredScopes.length > 0
? [...requiredScopes]
: [...new Set(resourceMetadata?.scopes_supported ?? [])]
if (refreshSupported && offlineAccessSupported && !recommendedScopes.includes("offline_access")) {
recommendedScopes.push("offline_access")
}
const supportsClientMetadata = authorizationServers.some((server) => server.clientIdMetadataDocumentSupported)
const supportsDynamic = authorizationServers.some((server) => Boolean(server.registrationEndpoint))
const availableRegistrationMethods: EnterpriseMcpConnectionRequirements["authentication"]["availableRegistrationMethods"] = ["pre_registered"]
if (supportsClientMetadata) availableRegistrationMethods.unshift("client_metadata")
if (supportsDynamic) availableRegistrationMethods.push("dynamic")
let recommendedRegistrationMethod: EnterpriseMcpConnectionRequirements["authentication"]["recommendedRegistrationMethod"] = "pre_registered"
if (supportsClientMetadata) recommendedRegistrationMethod = "client_metadata"
else if (supportsDynamic) recommendedRegistrationMethod = "dynamic"
const oauthDetected = Boolean(resourceMetadata || authorizationServers.length > 0)
const requirements = manualRequirements({ authorizationServers, authenticationRequired })
const status: EnterpriseMcpConnectionRequirements["status"] = initialize === "succeeded"
? "ready"
: !authenticationRequired && lastStatus === undefined
? "unreachable"
: oauthDetected && !requirements.some((requirement) => requirement.required)
? "ready"
: authenticationRequired
? "manual_action_required"
: "unsupported"
try {
return {
status,
server: {
url: serverUrl.toString(),
initialize,
...(protocolEra ? { protocolEra } : {}),
...(protocolVersion ? { protocolVersion } : {}),
},
authentication: {
kind: initialize === "succeeded" ? "none" : oauthDetected ? "oauth" : authenticationRequired ? "manual_bearer" : "unknown",
resource: resourceMetadata?.resource,
protectedResourceMetadataUrl: resourceMetadataUrl?.toString(),
authorizationServers,
requiredScopes,
recommendedScopes,
refreshSupport: refreshSupported ? "supported" : authorizationServers.length > 0 ? "not_advertised" : "unknown",
availableRegistrationMethods,
recommendedRegistrationMethod,
},
tools: initialize === "succeeded"
? { visibility: "available_without_auth", count: tools.length, items: tools }
: authenticationRequired
? { visibility: "requires_auth" }
: { visibility: "unavailable" },
manualRequirements: requirements,
warnings,
}
} finally {
clearTimeout(timeout)
}
}
@@ -0,0 +1,104 @@
import { Buffer } from "node:buffer"
import type { Client, RequestOptions } from "@modelcontextprotocol/client"
import { EnterpriseMcpCatalogError } from "./errors.js"
export const ENTERPRISE_MCP_RESOURCE_PAGE_LIMIT = 20
export const ENTERPRISE_MCP_RESOURCE_ITEM_LIMIT = 2_000
export const ENTERPRISE_MCP_RESOURCE_URI_LIMIT_BYTES = 16 * 1024
export const ENTERPRISE_MCP_RESOURCE_DESCRIPTOR_LIMIT_BYTES = 256 * 1024
export const ENTERPRISE_MCP_RESOURCE_CATALOG_LIMIT_BYTES = 8 * 1024 * 1024
export const ENTERPRISE_MCP_RESOURCE_RESULT_LIMIT_BYTES = 2 * 1024 * 1024
type ResourcePage = Awaited<ReturnType<Client["listResources"]>>
type ResourceTemplatePage = Awaited<ReturnType<Client["listResourceTemplates"]>>
function serializedBytes(value: unknown): number {
const serialized = JSON.stringify(value)
return serialized === undefined ? 0 : Buffer.byteLength(serialized, "utf8")
}
function assertDescriptor(value: { uri?: string; uriTemplate?: string }): number {
const uri = value.uri ?? value.uriTemplate ?? ""
if (Buffer.byteLength(uri, "utf8") > ENTERPRISE_MCP_RESOURCE_URI_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_RESOURCE_URI_LIMIT")
}
const bytes = serializedBytes(value)
if (bytes > ENTERPRISE_MCP_RESOURCE_DESCRIPTOR_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_RESOURCE_DESCRIPTOR_LIMIT")
}
return bytes
}
async function collectPages<T extends { uri?: string; uriTemplate?: string }>(input: {
listPage: (cursor: string | undefined, options: RequestOptions) => Promise<{
items: T[]
nextCursor?: string
}>
requestOptions: RequestOptions
}): Promise<T[]> {
const items: T[] = []
const identifiers = new Set<string>()
const cursors = new Set<string>()
let cursor: string | undefined
let catalogBytes = 0
for (let page = 0; page < ENTERPRISE_MCP_RESOURCE_PAGE_LIMIT; page += 1) {
const result = await input.listPage(cursor, input.requestOptions)
for (const item of result.items) {
if (items.length >= ENTERPRISE_MCP_RESOURCE_ITEM_LIMIT) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_ITEM_LIMIT")
}
const identifier = item.uri ?? item.uriTemplate ?? ""
if (identifiers.has(identifier)) throw new EnterpriseMcpCatalogError("MCP_CATALOG_DUPLICATE_RESOURCE")
const bytes = assertDescriptor(item)
if (catalogBytes + bytes > ENTERPRISE_MCP_RESOURCE_CATALOG_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_BYTE_LIMIT")
}
catalogBytes += bytes
identifiers.add(identifier)
items.push(item)
}
if (!result.nextCursor) return items
if (Buffer.byteLength(result.nextCursor, "utf8") > ENTERPRISE_MCP_RESOURCE_URI_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_CURSOR_SIZE_LIMIT")
}
if (cursors.has(result.nextCursor)) throw new EnterpriseMcpCatalogError("MCP_CATALOG_CURSOR_LOOP")
cursors.add(result.nextCursor)
cursor = result.nextCursor
}
throw new EnterpriseMcpCatalogError("MCP_CATALOG_PAGE_LIMIT")
}
export function collectEnterpriseMcpResources(input: {
listPage: (cursor: string | undefined, options: RequestOptions) => Promise<ResourcePage>
requestOptions: RequestOptions
}) {
return collectPages({
requestOptions: input.requestOptions,
listPage: async (cursor, options) => {
const result = await input.listPage(cursor, options)
return { items: result.resources, nextCursor: result.nextCursor }
},
})
}
export function collectEnterpriseMcpResourceTemplates(input: {
listPage: (cursor: string | undefined, options: RequestOptions) => Promise<ResourceTemplatePage>
requestOptions: RequestOptions
}) {
return collectPages({
requestOptions: input.requestOptions,
listPage: async (cursor, options) => {
const result = await input.listPage(cursor, options)
return { items: result.resourceTemplates, nextCursor: result.nextCursor }
},
})
}
export function assertEnterpriseMcpResourceResult(value: unknown): void {
if (serializedBytes(value) > ENTERPRISE_MCP_RESOURCE_RESULT_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_RESOURCE_RESULT_LIMIT")
}
}
@@ -0,0 +1,86 @@
const SENSITIVE_RESPONSE_KEY = /token|secret|password|assertion|code|key|authorization/i
const SENSITIVE_JSON_VALUE = /("(?:[^"\\]|\\.)*(?:token|secret|password|assertion|code|key|authorization)(?:[^"\\]|\\.)*"\s*:\s*)("(?:[^"\\]|\\.)*(?:"|$)|[^,}\]]*)/gi
const SENSITIVE_TEXT_PAIR = /((?:token|secret|password|assertion|code|key|authorization)[\w-]*\s*[=:]\s*)[^\s&"',;)]+/gi
const SENSITIVE_QUOTED_TEXT_PAIR = /(["'][\w-]*(?:token|secret|password|assertion|code|key|authorization)[\w-]*["']\s*:\s*["'])[^"']*(["'])/gi
const JWT_CREDENTIAL = /eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g
const SLACK_CREDENTIAL = /\bxox[a-z]-[A-Za-z0-9-]+|\bxoxe(?:-\d)?-[A-Za-z0-9-]+/gi
const BEARER_CREDENTIAL = /(\bBearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi
const GITHUB_CREDENTIAL = /\bgh[pousr]_[A-Za-z0-9]{20,}/gi
const LONG_OPAQUE_CREDENTIAL = /[A-Za-z0-9_~+/=-]{40,}/g
export const ENTERPRISE_MCP_RESPONSE_BODY_EXCERPT_CHARS = 2_000
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
export function redactedSensitiveResponseString(value: string): string {
return value
.replace(SENSITIVE_QUOTED_TEXT_PAIR, "$1[redacted]$2")
.replace(SENSITIVE_TEXT_PAIR, "$1[redacted]")
.replace(JWT_CREDENTIAL, "[redacted]")
.replace(SLACK_CREDENTIAL, "[redacted]")
.replace(BEARER_CREDENTIAL, "$1[redacted]")
.replace(GITHUB_CREDENTIAL, "[redacted]")
.replace(LONG_OPAQUE_CREDENTIAL, "[redacted]")
}
function redactJsonValue(value: unknown): unknown {
if (Array.isArray(value)) return value.map(redactJsonValue)
if (typeof value === "string") return redactedSensitiveResponseString(value)
if (!isRecord(value)) return value
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
key,
SENSITIVE_RESPONSE_KEY.test(key) ? "[redacted]" : redactJsonValue(entry),
]))
}
export function redactedResponseBodyExcerpt(text: string, limit = ENTERPRISE_MCP_RESPONSE_BODY_EXCERPT_CHARS): string {
let redacted = redactedSensitiveResponseString(text.replace(SENSITIVE_JSON_VALUE, '$1"[redacted]"'))
try {
const parsed: unknown = JSON.parse(text)
const serialized = JSON.stringify(redactJsonValue(parsed))
if (serialized !== undefined) redacted = serialized
} catch {
// A bounded excerpt may end mid-JSON. The conservative regex above still
// removes values whose sensitive key is visible in the excerpt.
}
return redacted.slice(0, limit)
}
async function responseTextExcerpt(response: Response, limit: number): Promise<string | null> {
if (!response.body) return null
const reader = response.body.getReader()
const decoder = new TextDecoder()
let text = ""
try {
while (text.length < limit) {
const next = await reader.read()
if (next.done) {
text += decoder.decode()
return text.slice(0, limit)
}
text += decoder.decode(next.value, { stream: true })
if (text.length >= limit) {
void reader.cancel().catch(() => undefined)
return text.slice(0, limit)
}
}
return text.slice(0, limit)
} catch {
return null
}
}
export async function boundedRedactedResponseBodyExcerpt(
response: Response,
limit = ENTERPRISE_MCP_RESPONSE_BODY_EXCERPT_CHARS,
): Promise<string | undefined> {
try {
const text = await responseTextExcerpt(response.clone(), limit)
return text === null ? undefined : redactedResponseBodyExcerpt(text, limit)
} catch {
return undefined
}
}
@@ -0,0 +1,134 @@
import type { EnterpriseMcpFetch, EnterpriseMcpRequestPhase } from "./contracts.js"
import { classifyEnterpriseMcpRequest } from "./request-observer.js"
import {
ENTERPRISE_MCP_RESPONSE_BODY_EXCERPT_CHARS,
redactedSensitiveResponseString,
} from "./response-body-excerpt.js"
type OAuthErrorCode = "invalid_grant" | "invalid_client" | "invalid_scope" | "access_denied" | "server_error"
type TokenRequestPhase = Extract<EnterpriseMcpRequestPhase, "oauth-token-exchange" | "oauth-token-refresh">
export const SLACK_STYLE_OAUTH_ERROR_MAPPING: Readonly<Record<string, OAuthErrorCode>> = Object.freeze({
invalid_code: "invalid_grant",
code_already_used: "invalid_grant",
token_expired: "invalid_grant",
token_revoked: "invalid_grant",
invalid_refresh_token: "invalid_grant",
bad_redirect_uri: "invalid_grant",
invalid_client_id: "invalid_client",
bad_client_secret: "invalid_client",
invalid_scope: "invalid_scope",
no_scopes: "invalid_scope",
no_user_scopes: "invalid_scope",
invalid_auth: "access_denied",
accesslimited: "access_denied",
access_denied: "access_denied",
})
export type EnterpriseMcpTokenResponseTranslation = {
requestPhase: TokenRequestPhase
outcome: "succeeded" | "failed"
httpStatus: number
responseBodyExcerpt: string
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
function isTokenRequestPhase(phase: EnterpriseMcpRequestPhase): phase is TokenRequestPhase {
return phase === "oauth-token-exchange" || phase === "oauth-token-refresh"
}
function structuredTokenResponseExcerpt(response: Record<string, unknown>): string {
const allowed: Record<string, unknown> = {}
if (typeof response.ok === "boolean") allowed.ok = response.ok
for (const field of ["error", "error_description", "error_uri", "message"]) {
const value = response[field]
if (typeof value === "string") allowed[field] = redactedSensitiveResponseString(value)
}
return JSON.stringify(allowed).slice(0, ENTERPRISE_MCP_RESPONSE_BODY_EXCERPT_CHARS)
}
function jsonResponse(body: Record<string, unknown>, source: Response, status: number): Response {
const headers = new Headers(source.headers)
headers.set("content-type", "application/json")
headers.delete("content-length")
return new Response(JSON.stringify(body), {
status,
statusText: status === source.status ? source.statusText : "Bad Request",
headers,
})
}
function notifyTranslation(
callback: ((translation: EnterpriseMcpTokenResponseTranslation) => void) | undefined,
translation: EnterpriseMcpTokenResponseTranslation,
): void {
try {
callback?.(translation)
} catch {
// Compatibility diagnostics must never change the response seen by the SDK.
}
}
export function createEnterpriseMcpTokenResponseCompat(input: {
fetch: EnterpriseMcpFetch
onTranslation?: (translation: EnterpriseMcpTokenResponseTranslation) => void
}): EnterpriseMcpFetch {
return async (rawUrl, init) => {
const response = await input.fetch(rawUrl, init)
const requestPhase = classifyEnterpriseMcpRequest(
rawUrl instanceof URL ? rawUrl : new URL(rawUrl),
init,
)
const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
if (!isTokenRequestPhase(requestPhase) || !response.ok || !contentType.includes("json")) return response
let text: string
let parsed: unknown
try {
text = await response.clone().text()
parsed = JSON.parse(text)
} catch {
return response
}
if (!isRecord(parsed)) return response
if (parsed.ok === false && typeof parsed.error === "string") {
const mappedError = SLACK_STYLE_OAUTH_ERROR_MAPPING[parsed.error] ?? "server_error"
const ipAllowlistHint = parsed.error === "invalid_auth"
? " (may indicate the app's IP allowlist rejects our egress IPs)"
: ""
const translated = jsonResponse({
error: mappedError,
error_description: `Slack-style provider error: ${parsed.error}${ipAllowlistHint}`,
}, response, 400)
notifyTranslation(input.onTranslation, {
requestPhase,
outcome: "failed",
httpStatus: translated.status,
responseBodyExcerpt: structuredTokenResponseExcerpt(parsed),
})
return translated
}
if (
parsed.ok === true
&& typeof parsed.token_type === "string"
&& parsed.token_type.length > 0
&& parsed.token_type.toLowerCase() !== "bearer"
) {
const translated = jsonResponse({ ...parsed, token_type: "Bearer" }, response, response.status)
notifyTranslation(input.onTranslation, {
requestPhase,
outcome: "succeeded",
httpStatus: translated.status,
responseBodyExcerpt: structuredTokenResponseExcerpt(parsed),
})
return translated
}
return response
}
}
@@ -0,0 +1,115 @@
import { Buffer } from "node:buffer"
import type { RequestOptions } from "@modelcontextprotocol/client"
import type { EnterpriseMcpTool } from "./contracts.js"
import { EnterpriseMcpCatalogError, type EnterpriseMcpCatalogErrorCode } from "./errors.js"
export const ENTERPRISE_MCP_TOOL_PAGE_LIMIT = 20
export const ENTERPRISE_MCP_TOOL_ITEM_LIMIT = 2_000
export const ENTERPRISE_MCP_TOOL_NAME_LIMIT_BYTES = 512
export const ENTERPRISE_MCP_TOOL_TITLE_LIMIT_BYTES = 4 * 1024
export const ENTERPRISE_MCP_TOOL_DESCRIPTION_LIMIT_BYTES = 64 * 1024
export const ENTERPRISE_MCP_TOOL_SCHEMA_LIMIT_BYTES = 512 * 1024
export const ENTERPRISE_MCP_TOOL_SCHEMA_DEPTH_LIMIT = 64
export const ENTERPRISE_MCP_CURSOR_LIMIT_BYTES = 16 * 1024
export const ENTERPRISE_MCP_CATALOG_LIMIT_BYTES = 8 * 1024 * 1024
type ToolPage = {
tools: EnterpriseMcpTool[]
nextCursor?: string
}
function serializedBytes(value: unknown): number {
const serialized = JSON.stringify(value)
return serialized === undefined ? 0 : Buffer.byteLength(serialized, "utf8")
}
function assertStringLimit(
value: string | undefined,
limit: number,
code: EnterpriseMcpCatalogErrorCode,
): void {
if (value !== undefined && serializedBytes(value) > limit) {
throw new EnterpriseMcpCatalogError(code)
}
}
function measureSchema(value: unknown): { bytes: number; depth: number; cyclic: boolean } {
type Frame = { value: unknown; depth: number; leaving?: object }
const stack: Frame[] = [{ value, depth: 0 }]
const active = new WeakSet<object>()
let maxDepth = 0
while (stack.length > 0) {
const frame = stack.pop()
if (!frame) break
if (frame.leaving) {
active.delete(frame.leaving)
continue
}
maxDepth = Math.max(maxDepth, frame.depth)
if (typeof frame.value !== "object" || frame.value === null) continue
if (active.has(frame.value)) return { bytes: 0, depth: maxDepth, cyclic: true }
active.add(frame.value)
stack.push({ value: null, depth: frame.depth, leaving: frame.value })
const children = Array.isArray(frame.value) ? frame.value : Object.values(frame.value)
for (const child of children) stack.push({ value: child, depth: frame.depth + 1 })
}
return { bytes: serializedBytes(value), depth: maxDepth, cyclic: false }
}
function assertSchema(schema: unknown): void {
const measurement = measureSchema(schema)
if (measurement.cyclic) throw new EnterpriseMcpCatalogError("MCP_CATALOG_SCHEMA_CYCLE")
if (measurement.depth > ENTERPRISE_MCP_TOOL_SCHEMA_DEPTH_LIMIT) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_SCHEMA_DEPTH_LIMIT")
}
if (measurement.bytes > ENTERPRISE_MCP_TOOL_SCHEMA_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_SCHEMA_SIZE_LIMIT")
}
}
function assertTool(tool: EnterpriseMcpTool): void {
assertStringLimit(tool.name, ENTERPRISE_MCP_TOOL_NAME_LIMIT_BYTES, "MCP_CATALOG_TOOL_NAME_LIMIT")
assertStringLimit(tool.title, ENTERPRISE_MCP_TOOL_TITLE_LIMIT_BYTES, "MCP_CATALOG_TOOL_TITLE_LIMIT")
assertStringLimit(tool.description, ENTERPRISE_MCP_TOOL_DESCRIPTION_LIMIT_BYTES, "MCP_CATALOG_TOOL_DESCRIPTION_LIMIT")
assertSchema(tool.inputSchema)
if (tool.outputSchema) assertSchema(tool.outputSchema)
}
export async function collectEnterpriseMcpTools(input: {
listPage: (cursor: string | undefined, options: RequestOptions) => Promise<ToolPage>
requestOptions: RequestOptions
}): Promise<EnterpriseMcpTool[]> {
const tools: EnterpriseMcpTool[] = []
const names = new Set<string>()
const cursors = new Set<string>()
let cursor: string | undefined
let catalogBytes = 0
for (let page = 0; page < ENTERPRISE_MCP_TOOL_PAGE_LIMIT; page += 1) {
const result = await input.listPage(cursor, input.requestOptions)
for (const tool of result.tools) {
if (tools.length >= ENTERPRISE_MCP_TOOL_ITEM_LIMIT) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_ITEM_LIMIT")
}
if (names.has(tool.name)) throw new EnterpriseMcpCatalogError("MCP_CATALOG_DUPLICATE_TOOL")
assertTool(tool)
const toolBytes = serializedBytes(tool)
if (catalogBytes + toolBytes > ENTERPRISE_MCP_CATALOG_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_BYTE_LIMIT")
}
catalogBytes += toolBytes
names.add(tool.name)
tools.push(tool)
}
if (!result.nextCursor) return tools
if (serializedBytes(result.nextCursor) > ENTERPRISE_MCP_CURSOR_LIMIT_BYTES) {
throw new EnterpriseMcpCatalogError("MCP_CATALOG_CURSOR_SIZE_LIMIT")
}
if (cursors.has(result.nextCursor)) throw new EnterpriseMcpCatalogError("MCP_CATALOG_CURSOR_LOOP")
cursors.add(result.nextCursor)
cursor = result.nextCursor
}
throw new EnterpriseMcpCatalogError("MCP_CATALOG_PAGE_LIMIT")
}
@@ -0,0 +1,68 @@
import { Buffer } from "node:buffer"
import { EnterpriseMcpToolInputError } from "./errors.js"
export const ENTERPRISE_MCP_TOOL_ARGUMENT_LIMIT_BYTES = 1024 * 1024
export const ENTERPRISE_MCP_TOOL_ARGUMENT_DEPTH_LIMIT = 64
export function assertEnterpriseMcpToolArguments(argumentsValue: Record<string, unknown>): void {
type Frame = { value: unknown; depth: number; leave?: object; key?: string }
const active = new WeakSet<object>()
const stack: Frame[] = [{ value: argumentsValue, depth: 0 }]
let bytes = 0
const add = (value: string): void => {
bytes += Buffer.byteLength(value, "utf8")
if (bytes > ENTERPRISE_MCP_TOOL_ARGUMENT_LIMIT_BYTES) {
throw new EnterpriseMcpToolInputError("MCP_TOOL_ARGUMENT_SIZE_LIMIT")
}
}
while (stack.length > 0) {
const frame = stack.pop()
if (!frame) break
if (frame.leave) {
active.delete(frame.leave)
continue
}
if (frame.depth > ENTERPRISE_MCP_TOOL_ARGUMENT_DEPTH_LIMIT) {
throw new EnterpriseMcpToolInputError("MCP_TOOL_ARGUMENT_DEPTH_LIMIT")
}
if (frame.key !== undefined) add(`${JSON.stringify(frame.key)}:`)
const current = frame.value
if (current === null || typeof current === "boolean") {
add(JSON.stringify(current))
continue
}
if (typeof current === "string") {
add(JSON.stringify(current))
continue
}
if (typeof current === "number") {
if (!Number.isFinite(current)) throw new EnterpriseMcpToolInputError("MCP_TOOL_ARGUMENT_INVALID_JSON")
add(JSON.stringify(current))
continue
}
if (typeof current !== "object") {
throw new EnterpriseMcpToolInputError("MCP_TOOL_ARGUMENT_INVALID_JSON")
}
const prototype = Object.getPrototypeOf(current)
if (!Array.isArray(current) && prototype !== Object.prototype && prototype !== null) {
throw new EnterpriseMcpToolInputError("MCP_TOOL_ARGUMENT_INVALID_JSON")
}
if (active.has(current)) throw new EnterpriseMcpToolInputError("MCP_TOOL_ARGUMENT_CYCLE")
active.add(current)
stack.push({ value: null, depth: frame.depth, leave: current })
if (Array.isArray(current)) {
add(`[${",".repeat(Math.max(0, current.length - 1))}]`)
for (let index = current.length - 1; index >= 0; index -= 1) {
stack.push({ value: current[index], depth: frame.depth + 1 })
}
continue
}
const entries = Object.entries(current)
add(`{${",".repeat(Math.max(0, entries.length - 1))}}`)
for (let index = entries.length - 1; index >= 0; index -= 1) {
const [key, value] = entries[index]!
stack.push({ value, key, depth: frame.depth + 1 })
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,46 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { SdkError, SdkErrorCode } from "@modelcontextprotocol/client"
import {
EnterpriseMcpClientError,
EnterpriseMcpLifecycleDeadlineError,
isEnterpriseMcpLifecycleDeadline,
} from "../src/index.js"
describe("lifecycle deadline error", () => {
it("aborts with an SdkError so the SDK rethrows it instead of stringifying the reason", () => {
const error = new EnterpriseMcpLifecycleDeadlineError("tool-execution")
// The SDK only passes an abort reason through untouched when it is already
// an SdkError; anything else becomes String(reason) on a new RequestTimeout.
assert.ok(error instanceof SdkError)
assert.equal(error.code, SdkErrorCode.RequestTimeout)
assert.equal(error.operationPhase, "tool-execution")
assert.match(error.message, /exceeded its lifecycle deadline/)
})
it("carries a marker that survives an SDK round trip", () => {
const reason = new EnterpriseMcpLifecycleDeadlineError("tool-execution")
const rethrown = reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason))
assert.ok(isEnterpriseMcpLifecycleDeadline(rethrown))
})
it("detects the deadline through a wrapped cause chain", () => {
const wrapped = new EnterpriseMcpClientError({
operationPhase: "tool-execution",
requestPhase: "mcp-tool-execution",
cause: new EnterpriseMcpLifecycleDeadlineError("tool-execution"),
})
assert.ok(isEnterpriseMcpLifecycleDeadline(wrapped))
})
it("does not claim a provider's own RequestTimeout as ours", () => {
const providerError = new SdkError(SdkErrorCode.RequestTimeout, "upstream is busy", { provider_detail: "busy" })
assert.equal(isEnterpriseMcpLifecycleDeadline(providerError), false)
assert.equal(isEnterpriseMcpLifecycleDeadline(new Error("unrelated")), false)
assert.equal(isEnterpriseMcpLifecycleDeadline(undefined), false)
})
})
@@ -0,0 +1,442 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { z } from "zod"
import {
discoverConnectionRequirements,
selectRecoverableAuthorizationServerIssuer,
type EnterpriseMcpFetch,
} from "../src/index.js"
const rpcRequestSchema = z.object({
id: z.union([z.string(), z.number()]).optional(),
method: z.string(),
}).passthrough()
function unauthenticatedMcpFetch(): EnterpriseMcpFetch {
return async (_url, init) => {
const body = typeof init?.body === "string" ? init.body : ""
if (!body) return new Response(null, { status: 202 })
const request = rpcRequestSchema.parse(JSON.parse(body))
if (request.method === "notifications/initialized") return new Response(null, { status: 202 })
if (request.method === "initialize") {
return Response.json({
jsonrpc: "2.0",
id: request.id,
result: {
protocolVersion: "2025-06-18",
capabilities: { tools: {} },
serverInfo: { name: "requirements-test", version: "1.0.0" },
},
})
}
if (request.method === "tools/list") {
return Response.json({
jsonrpc: "2.0",
id: request.id,
result: {
tools: [{
name: "read-record",
inputSchema: { type: "object" },
annotations: { readOnlyHint: true, destructiveHint: false },
}],
},
})
}
return new Response(null, { status: 404 })
}
}
describe("enterprise MCP requirements discovery", () => {
it("discovers a 2026 stateless server without an initialize handshake", async () => {
const methods: string[] = []
const fetch: EnterpriseMcpFetch = async (_url, init) => {
assert.equal(typeof init?.body, "string")
const request = rpcRequestSchema.parse(JSON.parse(init?.body as string))
methods.push(request.method)
assert.equal(new Headers(init?.headers).get("mcp-protocol-version"), "2026-07-28")
assert.equal(new Headers(init?.headers).has("mcp-session-id"), false)
if (request.method === "server/discover") {
return Response.json({
jsonrpc: "2.0",
id: request.id,
result: {
supportedVersions: ["2026-07-28"],
capabilities: { tools: {} },
resultType: "complete",
ttlMs: 0,
cacheScope: "private",
_meta: {
"io.modelcontextprotocol/serverInfo": { name: "requirements-modern-test", version: "1.0.0" },
},
},
})
}
if (request.method === "tools/list") {
return Response.json({
jsonrpc: "2.0",
id: request.id,
result: {
resultType: "complete",
ttlMs: 0,
cacheScope: "private",
tools: [{
name: "read-modern-record",
inputSchema: { type: "object" },
annotations: { readOnlyHint: true, destructiveHint: false },
}],
_meta: {
"io.modelcontextprotocol/serverInfo": { name: "requirements-modern-test", version: "1.0.0" },
},
},
})
}
return new Response(null, { status: 404 })
}
const result = await discoverConnectionRequirements({
serverUrl: "https://mcp.example.test/mcp",
fetch,
})
assert.deepEqual(methods, ["server/discover", "tools/list"])
assert.equal(result.status, "ready")
assert.equal(result.server.initialize, "succeeded")
assert.equal(result.server.protocolEra, "modern")
assert.equal(result.server.protocolVersion, "2026-07-28")
assert.equal(result.tools.items?.[0]?.name, "read-modern-record")
})
it("initializes and lists tools without creating registration state", async () => {
const result = await discoverConnectionRequirements({
serverUrl: "https://mcp.example.test/mcp",
fetch: unauthenticatedMcpFetch(),
})
assert.equal(result.status, "ready")
assert.equal(result.server.initialize, "succeeded")
assert.equal(result.authentication.kind, "none")
assert.equal(result.tools.visibility, "available_without_auth")
assert.equal(result.tools.count, 1)
assert.equal(result.tools.items?.[0]?.readOnlyHint, true)
})
it("discovers protected-resource and authorization-server requirements without performing DCR", async () => {
let registrationRequests = 0
const fetch: EnterpriseMcpFetch = async (url) => {
const target = new URL(url)
if (target.pathname === "/resource-metadata") {
return Response.json({
resource: "https://mcp.example.test/mcp",
authorization_servers: ["https://identity.example.test/tenant"],
scopes_supported: ["records.read", "records.write", "offline_access"],
})
}
if (target.pathname === "/.well-known/oauth-authorization-server/tenant") {
return Response.json({
issuer: "https://identity.example.test/tenant",
authorization_endpoint: "https://identity.example.test/tenant/authorize",
token_endpoint: "https://identity.example.test/tenant/token",
registration_endpoint: "https://identity.example.test/tenant/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["none"],
code_challenge_methods_supported: ["S256"],
client_id_metadata_document_supported: true,
scopes_supported: ["records.read", "records.write", "offline_access"],
})
}
if (target.pathname.endsWith("/register")) {
registrationRequests += 1
return new Response(null, { status: 500 })
}
return new Response(null, {
status: 401,
headers: {
"www-authenticate": "Bearer resource_metadata=\"https://mcp.example.test/resource-metadata\", scope=\"records.read\"",
},
})
}
const result = await discoverConnectionRequirements({
serverUrl: "https://mcp.example.test/mcp",
fetch,
})
assert.equal(result.server.initialize, "authentication_required")
assert.equal(result.authentication.kind, "oauth")
assert.deepEqual(result.authentication.requiredScopes, ["records.read"])
assert.deepEqual(result.authentication.recommendedScopes, ["records.read", "offline_access"])
assert.equal(result.authentication.recommendedRegistrationMethod, "client_metadata")
assert.deepEqual(result.authentication.availableRegistrationMethods, ["client_metadata", "pre_registered", "dynamic"])
assert.equal(result.authentication.refreshSupport, "supported")
assert.equal(result.tools.visibility, "requires_auth")
assert.equal(registrationRequests, 0)
})
it("requires explicit selection when protected-resource metadata advertises multiple issuers", async () => {
const issuers = ["https://identity-a.example.test", "https://identity-b.example.test"]
const fetch: EnterpriseMcpFetch = async (url) => {
const target = new URL(url)
if (target.pathname === "/resource-metadata") {
return Response.json({ resource: "https://mcp.example.test/mcp", authorization_servers: issuers })
}
const issuer = issuers.find((candidate) => target.origin === candidate)
if (issuer && target.pathname === "/.well-known/oauth-authorization-server") {
return Response.json({
issuer,
authorization_endpoint: `${issuer}/authorize`,
token_endpoint: `${issuer}/token`,
response_types_supported: ["code"],
client_id_metadata_document_supported: true,
})
}
return new Response(null, {
status: 401,
headers: { "www-authenticate": "Bearer resource_metadata=\"https://mcp.example.test/resource-metadata\"" },
})
}
const result = await discoverConnectionRequirements({
serverUrl: "https://mcp.example.test/mcp",
fetch,
})
assert.equal(result.status, "manual_action_required")
assert.equal(result.authentication.authorizationServers.length, 2)
assert.equal(result.manualRequirements[0]?.code, "authorization_server_selection")
assert.equal(result.manualRequirements[0]?.required, true)
})
it("accepts a resource-scoped OAuth discovery alias while exposing the canonical issuer", async () => {
const resource = "https://api.salesforce.example:443/platform/mcp/v1/platform/sobject-all"
const fetch: EnterpriseMcpFetch = async (url) => {
const target = new URL(url)
if (target.pathname === "/.well-known/oauth-protected-resource/platform/mcp/v1/platform/sobject-all") {
return Response.json({
resource,
authorization_servers: [resource],
scopes_supported: ["mcp_api", "refresh_token"],
})
}
if (target.pathname === "/.well-known/oauth-authorization-server/platform/mcp/v1/platform/sobject-all") {
return Response.json({
issuer: "https://login.salesforce.example",
authorization_endpoint: "https://login.salesforce.example/services/oauth2/authorize",
token_endpoint: "https://login.salesforce.example/services/oauth2/token",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["none", "client_secret_post"],
code_challenge_methods_supported: ["S256"],
scopes_supported: ["mcp_api", "refresh_token"],
})
}
if (target.origin === "https://login.salesforce.example" && target.pathname === "/.well-known/oauth-authorization-server") {
return Response.json({
issuer: "https://login.salesforce.example",
authorization_endpoint: "https://login.salesforce.example/services/oauth2/authorize",
token_endpoint: "https://login.salesforce.example/services/oauth2/token",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["none", "client_secret_post"],
code_challenge_methods_supported: ["S256"],
scopes_supported: ["mcp_api", "refresh_token"],
})
}
return new Response(null, { status: 401 })
}
const result = await discoverConnectionRequirements({
serverUrl: "https://api.salesforce.example/platform/mcp/v1/platform/sobject-all",
fetch,
})
assert.equal(result.authentication.authorizationServers[0]?.issuer, "https://login.salesforce.example")
assert.deepEqual(result.authentication.authorizationServers[0]?.scopesSupported, ["mcp_api", "refresh_token"])
assert.deepEqual(result.authentication.recommendedScopes, ["mcp_api", "refresh_token"])
assert.equal(result.authentication.recommendedRegistrationMethod, "pre_registered")
assert.equal(result.warnings.some((warning) => warning.code === "oauth_issuer_mismatch"), false)
assert.equal(selectRecoverableAuthorizationServerIssuer({
selectedIssuer: resource,
requirements: result,
}), "https://login.salesforce.example")
})
it("accepts a root resource discovery alias with an equivalent trailing slash", async () => {
const fetch: EnterpriseMcpFetch = async (url) => {
const target = new URL(url)
if (target.origin === "https://mcp.vercel.example" && target.pathname === "/.well-known/oauth-protected-resource") {
return Response.json({
resource: "https://mcp.vercel.example/",
authorization_servers: ["https://mcp.vercel.example"],
})
}
if (target.origin === "https://mcp.vercel.example" && target.pathname === "/.well-known/oauth-authorization-server") {
return Response.json({
issuer: "https://vercel.example",
authorization_endpoint: "https://vercel.example/oauth/authorize",
token_endpoint: "https://vercel.example/oauth/token",
registration_endpoint: "https://vercel.example/oauth/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["none"],
code_challenge_methods_supported: ["S256"],
})
}
if (target.origin === "https://vercel.example" && target.pathname === "/.well-known/oauth-authorization-server") {
return Response.json({
issuer: "https://vercel.example",
authorization_endpoint: "https://vercel.example/oauth/authorize",
token_endpoint: "https://vercel.example/oauth/token",
registration_endpoint: "https://vercel.example/oauth/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["none"],
code_challenge_methods_supported: ["S256"],
})
}
return new Response(null, {
status: 401,
headers: {
"www-authenticate": "Bearer resource_metadata=\"https://mcp.vercel.example/.well-known/oauth-protected-resource\"",
},
})
}
const result = await discoverConnectionRequirements({
serverUrl: "https://mcp.vercel.example",
fetch,
})
assert.equal(result.authentication.authorizationServers[0]?.issuer, "https://vercel.example")
assert.equal(result.authentication.recommendedRegistrationMethod, "dynamic")
assert.equal(result.warnings.some((warning) => warning.code === "oauth_issuer_mismatch"), false)
assert.equal(selectRecoverableAuthorizationServerIssuer({
selectedIssuer: "https://mcp.vercel.example",
requirements: result,
}), "https://vercel.example")
assert.equal(selectRecoverableAuthorizationServerIssuer({
selectedIssuer: "https://unrelated.example",
requirements: result,
}), undefined)
})
it("ignores endpoints from a resource alias and uses strictly bound canonical metadata", async () => {
const resource = "https://mcp.example.test/mcp"
const issuer = "https://identity.example.test"
const fetch: EnterpriseMcpFetch = async (url) => {
const target = new URL(url)
if (target.origin === "https://mcp.example.test" && target.pathname === "/.well-known/oauth-protected-resource/mcp") {
return Response.json({ resource, authorization_servers: [resource] })
}
if (target.origin === "https://mcp.example.test" && target.pathname === "/.well-known/oauth-authorization-server/mcp") {
return Response.json({
issuer,
authorization_endpoint: "https://attacker.example.test/authorize",
token_endpoint: "https://attacker.example.test/token",
registration_endpoint: "https://attacker.example.test/register",
response_types_supported: ["code"],
})
}
if (target.origin === "https://identity.example.test" && target.pathname === "/.well-known/oauth-authorization-server") {
return Response.json({
issuer,
authorization_endpoint: `${issuer}/authorize`,
token_endpoint: `${issuer}/token`,
response_types_supported: ["code"],
})
}
return new Response(null, {
status: 401,
headers: { "www-authenticate": "Bearer resource_metadata=\"https://mcp.example.test/.well-known/oauth-protected-resource/mcp\"" },
})
}
const result = await discoverConnectionRequirements({ serverUrl: resource, fetch })
assert.equal(result.authentication.authorizationServers[0]?.issuer, issuer)
assert.equal(result.authentication.authorizationServers[0]?.authorizationEndpoint, `${issuer}/authorize`)
assert.equal(result.authentication.authorizationServers[0]?.tokenEndpoint, `${issuer}/token`)
assert.equal(result.authentication.authorizationServers[0]?.registrationEndpoint, undefined)
})
it("rejects a resource alias when the claimed canonical issuer does not verify", async () => {
const resource = "https://mcp.example.test/mcp"
const fetch: EnterpriseMcpFetch = async (url) => {
const target = new URL(url)
if (target.origin === "https://mcp.example.test" && target.pathname === "/.well-known/oauth-protected-resource/mcp") {
return Response.json({ resource, authorization_servers: [resource] })
}
if (target.origin === "https://mcp.example.test" && target.pathname === "/.well-known/oauth-authorization-server/mcp") {
return Response.json({
issuer: "https://identity.example.test",
authorization_endpoint: "https://attacker.example.test/authorize",
token_endpoint: "https://attacker.example.test/token",
response_types_supported: ["code"],
})
}
if (target.origin === "https://identity.example.test" && target.pathname === "/.well-known/oauth-authorization-server") {
return Response.json({
issuer: "https://different.example.test",
authorization_endpoint: "https://attacker.example.test/authorize",
token_endpoint: "https://attacker.example.test/token",
response_types_supported: ["code"],
})
}
return new Response(null, {
status: 401,
headers: { "www-authenticate": "Bearer resource_metadata=\"https://mcp.example.test/.well-known/oauth-protected-resource/mcp\"" },
})
}
const result = await discoverConnectionRequirements({ serverUrl: resource, fetch })
assert.equal(result.authentication.authorizationServers.length, 0)
assert.equal(result.authentication.authorizationServers.some((server) => server.tokenEndpoint?.includes("attacker.example.test")), false)
assert.equal(result.warnings.some((warning) => warning.code === "oauth_issuer_mismatch"), true)
assert.equal(result.status, "manual_action_required")
})
it("accepts an authorization-server root issuer with an equivalent trailing slash", async () => {
const fetch: EnterpriseMcpFetch = async (url) => {
const target = new URL(url)
if (target.origin === "https://mcp.close.example" && target.pathname === "/.well-known/oauth-protected-resource") {
return Response.json({
resource: "https://mcp.close.example/",
authorization_servers: ["https://api.close.example/"],
scopes_supported: ["mcp.read", "offline_access"],
})
}
if (target.origin === "https://api.close.example" && target.pathname === "/.well-known/oauth-authorization-server") {
return Response.json({
issuer: "https://api.close.example",
authorization_endpoint: "https://app.close.example/oauth2/authorize/",
token_endpoint: "https://api.close.example/oauth2/token/",
registration_endpoint: "https://api.close.example/oauth2/register/",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["none", "client_secret_basic", "client_secret_post"],
code_challenge_methods_supported: ["S256"],
scopes_supported: ["mcp.read", "offline_access"],
})
}
return new Response(null, {
status: 401,
headers: {
"www-authenticate": "Bearer resource_metadata=\"https://mcp.close.example/.well-known/oauth-protected-resource\"",
},
})
}
const result = await discoverConnectionRequirements({
serverUrl: "https://mcp.close.example/mcp",
fetch,
})
assert.equal(result.authentication.authorizationServers[0]?.issuer, "https://api.close.example")
assert.equal(result.authentication.recommendedRegistrationMethod, "dynamic")
assert.equal(result.warnings.some((warning) => warning.code === "oauth_issuer_mismatch"), false)
assert.equal(selectRecoverableAuthorizationServerIssuer({
selectedIssuer: "https://api.close.example/",
requirements: result,
}), "https://api.close.example")
})
})
@@ -0,0 +1,261 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"
import { exchangeAuthorization, OAuthError, OAuthErrorCode } from "@modelcontextprotocol/client"
import { z } from "zod"
import {
createEnterpriseMcpClient,
createEnterpriseMcpTokenResponseCompat,
SLACK_STYLE_OAUTH_ERROR_MAPPING,
type EnterpriseMcpConnection,
type EnterpriseMcpDiagnosticEvent,
} from "../src/index.js"
import { createEnterpriseMcpRequestObserver } from "../src/request-observer.js"
import { redactedResponseBodyExcerpt } from "../src/response-body-excerpt.js"
const SAFE_SLACK_ERROR = "Slack-style provider error: invalid_refresh_token"
const AUTHORIZATION_CODE = "SECRETVALUE123"
const JWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.signatureABCD"
const SLACK_REFRESH_TOKEN = "xoxe-1-1234567890-abcdef"
const BEARER_TOKEN = "Bearer abcdefghijklmnopqrstuvwx"
const GITHUB_TOKEN = "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"
const OPAQUE_TOKEN = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"
const tokenResponseSchema = z.object({
ok: z.boolean().optional(),
access_token: z.string(),
token_type: z.string(),
}).passthrough()
const discoverRequestSchema = z.object({
id: z.union([z.string(), z.number()]),
method: z.literal("server/discover"),
params: z.object({ _meta: z.record(z.string(), z.unknown()) }).passthrough(),
}).passthrough()
function tokenRequestInit(): RequestInit {
return {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "authorization_code", code: "approved-code" }),
}
}
function noAuthConnection(): EnterpriseMcpConnection {
return {
id: "slack-compat-connection",
serverUrl: "https://mcp.example.test/mcp",
authorization: { type: "none" },
}
}
describe("Slack-style MCP compatibility", () => {
it("maps the documented provider errors from one exported table", () => {
assert.equal(SLACK_STYLE_OAUTH_ERROR_MAPPING.invalid_code, "invalid_grant")
assert.equal(SLACK_STYLE_OAUTH_ERROR_MAPPING.bad_client_secret, "invalid_client")
assert.equal(SLACK_STYLE_OAUTH_ERROR_MAPPING.no_user_scopes, "invalid_scope")
assert.equal(SLACK_STYLE_OAUTH_ERROR_MAPPING.invalid_auth, "access_denied")
})
it("turns an HTTP-200 ok:false token exchange into a typed OAuth error", async () => {
const translations: EnterpriseMcpDiagnosticEvent[] = []
const compatibleFetch = createEnterpriseMcpTokenResponseCompat({
fetch: async () => Response.json({
ok: false,
error: "invalid_code",
access_token: "must-not-be-diagnosed",
weird_field: "xoxp-arbitrary",
}),
onTranslation: (translation) => translations.push({
kind: "request",
connectionId: "slack-compat-connection",
operationPhase: "authorization-callback",
...translation,
}),
})
const sdkFetch: typeof fetch = async (url, init) => compatibleFetch(
typeof url === "string" || url instanceof URL ? url : url.url,
init,
)
await assert.rejects(
exchangeAuthorization("https://provider.example.test", {
metadata: {
issuer: "https://provider.example.test",
authorization_endpoint: "https://provider.example.test/authorize",
token_endpoint: "https://provider.example.test/token",
response_types_supported: ["code"],
},
clientInformation: { client_id: "enterprise-client" },
authorizationCode: "approved-code",
codeVerifier: "pkce-verifier",
redirectUri: "https://den.example.test/callback",
fetchFn: sdkFetch,
}),
(error: unknown) => {
assert.ok(error instanceof OAuthError)
assert.equal(error.code, OAuthErrorCode.InvalidGrant)
assert.match(error.message, /Slack-style provider error: invalid_code/)
return true
},
)
assert.equal(translations.length, 1)
const translation = translations[0]
assert.ok(translation && translation.kind !== "credential-invalidation")
assert.equal(translation.httpStatus, 400)
assert.match(translation.responseBodyExcerpt ?? "", /invalid_code/)
assert.doesNotMatch(translation.responseBodyExcerpt ?? "", /must-not-be-diagnosed/)
assert.doesNotMatch(translation.responseBodyExcerpt ?? "", /weird_field|xoxp-arbitrary/)
})
it("normalizes a non-Bearer token_type while preserving other token fields", async () => {
const compatibleFetch = createEnterpriseMcpTokenResponseCompat({
fetch: async () => Response.json({
ok: true,
access_token: "xoxp-secret-token",
token_type: "user",
scope: "search:read",
}),
})
const response = await compatibleFetch("https://provider.example.test/token", tokenRequestInit())
const body = tokenResponseSchema.parse(await response.json())
assert.equal(body.token_type, "Bearer")
assert.equal(body.access_token, "xoxp-secret-token")
assert.equal(body.scope, "search:read")
})
it("passes standard token responses through as the original Response", async () => {
const original = Response.json({ access_token: "standard-token", token_type: "Bearer" })
const compatibleFetch = createEnterpriseMcpTokenResponseCompat({ fetch: async () => original })
assert.strictEqual(
await compatibleFetch("https://provider.example.test/token", tokenRequestInit()),
original,
)
})
it("negotiates the stateless protocol without initialize or a session id", async () => {
const methods: string[] = []
const headers: Headers[] = []
const events: EnterpriseMcpDiagnosticEvent[] = []
const client = createEnterpriseMcpClient({
diagnosticSink: (event) => events.push(event),
fetch: async (_url, init) => {
headers.push(new Headers(init?.headers))
const body = init?.body
assert.equal(typeof body, "string")
const parsed: unknown = JSON.parse(body as string)
const request = discoverRequestSchema.parse(parsed)
methods.push(request.method)
return Response.json({
jsonrpc: "2.0" as const,
id: request.id,
result: {
supportedVersions: ["2026-07-28"],
capabilities: {},
_meta: {
"io.modelcontextprotocol/serverInfo": { name: "stateless-test", version: "1.0.0" },
},
},
})
},
})
assert.deepEqual(await client.connect({
connection: noAuthConnection(),
redirectUri: "https://den.example.test/callback",
}), { status: "connected" })
assert.deepEqual(methods, ["server/discover"])
assert.equal(headers[0]?.get("mcp-protocol-version"), "2026-07-28")
assert.equal(headers[0]?.get("mcp-method"), "server/discover")
assert.equal(headers[0]?.has("mcp-session-id"), false)
assert.equal(events.filter((event) => event.kind !== "credential-invalidation"
&& event.protocolEra === "modern"
&& event.protocolVersion === "2026-07-28").length, 1)
})
for (const status of [401, 500]) {
it(`does not downgrade the discovery probe after HTTP ${status}`, async () => {
let protocolRequests = 0
const client = createEnterpriseMcpClient({
fetch: async (_url, init) => {
if (typeof init?.body === "string") protocolRequests += 1
return Response.json({ error: "provider_rejected" }, { status })
},
})
await assert.rejects(client.connect({
connection: noAuthConnection(),
redirectUri: "https://den.example.test/callback",
}))
assert.equal(protocolRequests, 1)
})
}
it("captures a bounded MCP error body excerpt with sensitive values redacted", async () => {
const events: EnterpriseMcpDiagnosticEvent[] = []
const originalBody = {
error: "provider_rejected",
access_token: "must-not-appear",
authorization_code: "also-secret",
}
const observer = createEnterpriseMcpRequestObserver({
connectionId: "slack-compat-connection",
operationPhase: "connection-handshake",
fetch: async () => Response.json(originalBody, { status: 400 }),
diagnosticSink: (event) => events.push(event),
signal: new AbortController().signal,
clock: { now: () => Date.now() },
})
const response = await observer.fetch("https://mcp.example.test/mcp", {
method: "POST",
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
})
assert.deepEqual(await response.json(), originalBody)
const failed = events.find((event) => event.kind === "request" && event.outcome === "failed")
assert.ok(failed && failed.kind !== "credential-invalidation")
assert.match(failed.responseBodyExcerpt ?? "", /\[redacted\]/)
assert.doesNotMatch(failed.responseBodyExcerpt ?? "", /must-not-appear|also-secret/)
assert.ok((failed.responseBodyExcerpt?.length ?? 0) <= 2_000)
})
it("redacts credential content inside non-sensitive fields and raw text", () => {
const errorDescription = [
SAFE_SLACK_ERROR,
`authorization_code=${AUTHORIZATION_CODE}`,
JWT,
SLACK_REFRESH_TOKEN,
BEARER_TOKEN,
GITHUB_TOKEN,
OPAQUE_TOKEN,
].join("; ")
const excerpt = redactedResponseBodyExcerpt(JSON.stringify({
error_description: errorDescription,
access_token: "key-based-secret",
}))
assert.match(excerpt, new RegExp(SAFE_SLACK_ERROR))
assert.match(excerpt, /authorization_code=\[redacted\]/)
assert.match(excerpt, /"access_token":"\[redacted\]"/)
for (const secret of [
AUTHORIZATION_CODE,
JWT,
SLACK_REFRESH_TOKEN,
"abcdefghijklmnopqrstuvwx",
GITHUB_TOKEN,
OPAQUE_TOKEN,
"key-based-secret",
]) {
assert.doesNotMatch(excerpt, new RegExp(secret))
}
assert.ok(excerpt.length <= 2_000)
const rawExcerpt = redactedResponseBodyExcerpt(
`not-json ${SAFE_SLACK_ERROR}; authorization_code=${AUTHORIZATION_CODE}; ${JWT}; ${SLACK_REFRESH_TOKEN}`,
)
assert.match(rawExcerpt, new RegExp(SAFE_SLACK_ERROR))
assert.match(rawExcerpt, /authorization_code=\[redacted\]/)
assert.doesNotMatch(rawExcerpt, new RegExp(`${AUTHORIZATION_CODE}|${JWT}|${SLACK_REFRESH_TOKEN}`))
})
})
@@ -0,0 +1,239 @@
/**
* Runnable demo for the terminal-401 credential guard (legacy flow
* enterprise-mcp-terminal-401-guard). Drives the real createEnterpriseMcpClient
* through three provider scenarios and prints machine-readable evidence:
*
* act 1 tool execution gets a transient 401 (no WWW-Authenticate proof)
* -> the stored credential must survive
* act 2 a background tool-discovery probe gets 401 + invalid_token
* -> the stored credential must survive (probes never invalidate)
* act 3 tool execution gets 401 + invalid_token proof
* -> the credential is invalidated once and a credential-invalidation
* diagnostic is emitted
*
* Output: human-readable act lines plus a final DEMO_RESULT_JSON=<json> line.
*/
import { z } from "zod"
import {
createEnterpriseMcpClient,
type EnterpriseMcpConnection,
type EnterpriseMcpDiagnosticEvent,
type EnterpriseMcpFetch,
type EnterpriseMcpOAuthAuthorizationHandle,
type EnterpriseMcpOAuthClientRegistration,
type EnterpriseMcpOAuthCredential,
type EnterpriseMcpOAuthPersistence,
} from "../src/index.js"
import type { OAuthClientInformationMixed, OAuthDiscoveryState, OAuthTokens } from "@modelcontextprotocol/client"
const rpcRequestSchema = z.object({
id: z.union([z.string(), z.number()]).nullish(),
method: z.string(),
})
class DemoOAuthPersistence implements EnterpriseMcpOAuthPersistence {
registration: EnterpriseMcpOAuthClientRegistration | undefined
credential: EnterpriseMcpOAuthCredential | undefined
invalidationCount = 0
private revision = 0
private discoveryState: OAuthDiscoveryState | undefined
private readonly authorizationRecords = new Map<
string,
{ handle: EnterpriseMcpOAuthAuthorizationHandle; codeVerifier: string }
>()
private nextRevision(): string {
this.revision += 1
return `revision-${this.revision}`
}
readonly clientRegistrations = {
load: async () => this.registration,
save: async (input: {
clientInformation: OAuthClientInformationMixed
expiresAt?: number
source: "client-metadata" | "dynamic"
}) => {
if (!this.registration) {
this.registration = {
clientInformation: input.clientInformation,
revision: this.nextRevision(),
expiresAt: input.expiresAt,
source: input.source,
}
}
return this.registration
},
invalidate: async () => {
this.registration = undefined
},
}
readonly authorizations = {
begin: async (input: {
id: string
codeVerifier: string
expiresAt: number
clientRegistrationRevision?: string
}) => {
this.authorizationRecords.set(input.id, {
handle: {
id: input.id,
revision: this.nextRevision(),
expiresAt: input.expiresAt,
clientRegistrationRevision: input.clientRegistrationRevision,
},
codeVerifier: input.codeVerifier,
})
},
load: async (input: { id: string }) => this.authorizationRecords.get(input.id),
invalidate: async (input: { id: string }) => {
this.authorizationRecords.delete(input.id)
},
}
readonly discovery = {
load: async () => this.discoveryState,
save: async (input: { state: OAuthDiscoveryState }) => {
this.discoveryState = input.state
},
invalidate: async () => {
this.discoveryState = undefined
},
}
readonly credentials = {
load: async () => this.credential,
save: async (input: { tokens: OAuthTokens; expiresAt?: number }) => {
this.credential = {
tokens: input.tokens,
expiresAt: input.expiresAt,
revision: this.nextRevision(),
}
},
invalidate: async () => {
this.credential = undefined
this.invalidationCount += 1
},
}
seed(): void {
this.registration = {
clientInformation: { client_id: "demo-client" },
revision: this.nextRevision(),
source: "pre-registered",
}
this.credential = {
tokens: { access_token: "demo-access-token", token_type: "Bearer" },
revision: this.nextRevision(),
}
}
}
function scriptedProviderFetch(input: {
rejectMethod: "tools/call" | "tools/list"
status: number
wwwAuthenticate?: string
}): EnterpriseMcpFetch {
return async (_url, init) => {
const body = typeof init?.body === "string" ? init.body : undefined
if (!body) return new Response(null, { status: 202 })
const request = rpcRequestSchema.parse(JSON.parse(body))
if (request.method === "notifications/initialized") return new Response(null, { status: 202 })
if (request.method === "initialize") {
return Response.json({
jsonrpc: "2.0",
id: request.id,
result: {
protocolVersion: "2025-06-18",
capabilities: { tools: {} },
serverInfo: { name: "terminal-401-guard-demo", version: "1.0.0" },
},
})
}
if (request.method === input.rejectMethod) {
const headers = new Headers()
if (input.wwwAuthenticate) headers.set("www-authenticate", input.wwwAuthenticate)
return new Response(null, { status: input.status, headers })
}
if (request.method === "tools/list") {
return Response.json({
jsonrpc: "2.0",
id: request.id,
result: { tools: [{ name: "demo-tool", inputSchema: { type: "object", properties: {} } }] },
})
}
return new Response(null, { status: 404 })
}
}
type ActResult = {
act: string
operation: "tools/call" | "tools/list"
providerResponse: string
credentialIntact: boolean
invalidationCount: number
invalidationDiagnostics: EnterpriseMcpDiagnosticEvent[]
}
async function runAct(input: {
act: string
operation: "tools/call" | "tools/list"
status: number
wwwAuthenticate?: string
}): Promise<ActResult> {
const persistence = new DemoOAuthPersistence()
persistence.seed()
const events: EnterpriseMcpDiagnosticEvent[] = []
const client = createEnterpriseMcpClient({
fetch: scriptedProviderFetch({
rejectMethod: input.operation,
status: input.status,
wwwAuthenticate: input.wwwAuthenticate,
}),
diagnosticSink: (event) => events.push(event),
})
const connection: EnterpriseMcpConnection = {
id: `demo-${input.act}`,
serverUrl: "https://mcp.example.test/mcp",
authorization: { type: "oauth", persistence },
}
const operation = input.operation === "tools/call"
? client.callTool({ connection, redirectUri: "https://den.example.test/oauth/callback", toolName: "demo-tool", arguments: {} })
: client.listTools({ connection, redirectUri: "https://den.example.test/oauth/callback" })
const rejected = await operation.then(() => false, () => true)
if (!rejected) throw new Error(`act "${input.act}" expected the provider rejection to surface`)
return {
act: input.act,
operation: input.operation,
providerResponse: `${input.status}${input.wwwAuthenticate ? ` with WWW-Authenticate: ${input.wwwAuthenticate}` : " without a WWW-Authenticate challenge"}`,
credentialIntact: persistence.credential?.tokens.access_token === "demo-access-token",
invalidationCount: persistence.invalidationCount,
invalidationDiagnostics: events.filter((event) => event.kind === "credential-invalidation"),
}
}
const acts: ActResult[] = [
await runAct({ act: "transient-401-on-execute", operation: "tools/call", status: 401 }),
await runAct({
act: "invalid-token-on-discovery-probe",
operation: "tools/list",
status: 401,
wwwAuthenticate: 'Bearer error="invalid_token"',
}),
await runAct({
act: "invalid-token-on-execute",
operation: "tools/call",
status: 401,
wwwAuthenticate: 'Bearer error="invalid_token"',
}),
]
for (const act of acts) {
console.log(
`act=${act.act} operation=${act.operation} provider=${act.providerResponse} `
+ `credentialIntact=${act.credentialIntact} invalidations=${act.invalidationCount} `
+ `invalidationDiagnostics=${act.invalidationDiagnostics.length}`,
)
}
console.log(`DEMO_RESULT_JSON=${JSON.stringify(acts)}`)
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"outDir": "dist"
},
"include": ["src", "test"]
}
@@ -0,0 +1,12 @@
import { defineConfig } from "tsup"
export default defineConfig({
clean: true,
dts: true,
entry: {
index: "src/index.ts",
},
format: ["esm"],
platform: "node",
target: "es2022",
})