Skip to content

Commit 7064615

Browse files
feat(connector-mcp): an OAuth-protected MCP server is connected through the MCP authorization flow and dispatched with each organization's token (ADR-0143 S2) (#28437)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoHgewSpchhjBvPu7yhxUUJx)_ Part of #26702 Clause-②: yes (widening) Metadata-protocol: semantic Skills-docs: the skills half (skills/objectstack-automation/references/integration-recipes.md) is #28299, the skills lane's card; content/docs/automation/connectors.mdx is updated here. ## 维护者速读 - 改了什么:内置 `mcp` 连接器现在也能调用需要 OAuth 的 MCP 服务器(如 Notion、HubSpot 的 MCP)。管理员点「连接」时,平台自动发现对方的授权服务器、注册客户端(或使用声明的 `clientId`),之后每个组织用自己的令牌、自己的会话调用。 - 为什么改:#28399 已让 `rest` / `openapi` 接入凭证句柄,但 `mcp` 实例仍只能降级;ADR-0143 S2 要求 MCP 按其授权规范在 http 上完成发现、动态注册和 PKCE。 - 风险与回滚:只影响在 `mcp` 上声明了 `oauth2` / `app-credential` 的实例(原来都是降级状态);`sys_connector_connection` 新增一个加密字段 `registered_client`;静态凭证的 `mcp` 实例行为不变。回滚即还原本 PR,这些实例回到降级。 - 先看:`packages/services/service-automation/src/oauth2-grant/mcp-authorization.ts`(发现与注册)、`plugin.ts` 中 `mcpAuthorizationClient` 与 `askingDuringMaterializationAs`(按裁定 B 选列工具的连接)、`packages/connectors/connector-mcp/src/mcp-provider.ts`(每次请求取令牌、每组织一个会话)。 - 两分钟验证:`pnpm --filter @objectstack/service-automation exec vitest run src/connector-mcp-authorization-door.test.ts`,预期 14 个用例全部通过,其中包括三个组织依次连接、最早连接的组织撤销后改用下一个组织列工具的端到端用例。 - 需要你做的:无,席位落地(新增连接表字段,契约复审由席位安排)。 ## What changes ADR-0143 S2, second half: the `mcp` provider. #28399 served `oauth2` and `app-credential` through the credential handle on `rest` and `openapi`; an `mcp` instance with either kind was still held degraded, and an `authorization_code` instance that left its endpoints to discovery was "not served". **`@objectstack/service-automation`: the MCP authorization flow at connect** - `oauth2-grant/mcp-authorization.ts` runs the flow for an `authorization_code` instance on `provider: 'mcp'` over `http` that leaves its endpoints or client undeclared: - Protected-resource metadata (RFC 9728), path-aware then root; its `resource` must be the declared server (same origin, equal or a prefix), and its first authorization server must be https. - Authorization-server metadata (RFC 8414, then OpenID Connect discovery); the `issuer` must equal the one asked for, and `S256` must be listed. - Dynamic client registration (RFC 7591) as a public client (`token_endpoint_auth_method: none`) for the deployment's redirect URI. A declared `clientId` skips registration (the pre-registered form). No registration endpoint and no `clientId` is refused, naming the form. - Declared fields win over discovered ones. Every URL must be https (loopback http only); no request follows a redirect; a server that does not answer, or answers `429` / `5xx`, is `CONNECTOR_UPSTREAM_UNAVAILABLE` (the door's `503`), and a missing or failing document is a `400`. A refusal names only the step and, for registration, the RFC 7591 error code, never the server's text. - `plugin.ts`, the connect flow (`beginConnectorConnection` / `completeConnectorConnection`): the authorization URL, the code exchange and every refresh use the discovered endpoints and client, and carry the resource indicator (RFC 8707). A callback whose `iss` differs from the discovered issuer is refused before its code is exchanged (RFC 9207). A reconnect reuses the client the organization's row keeps instead of registering again. - `sys_connector_connection` gains **`registered_client`**, a `Field.secret` (encrypted, masked) holding the discovered endpoints, the client id and any client secret the registration issued. A declared client's secret stays behind its `credentialRef` and is not copied in. `ConnectorConnectionStore.connect` writes it; `resolveRegisteredClient` reads it. - `oauth2-grant/grant-handle.ts`: `tokenUrl` / `clientId` are optional for an `authorization_code` instance; a refresh uses the declared client or the client the connection keeps, and a connection that keeps none is "reconnect required". - The materializer guard: an `oauth2` instance on `mcp` over `http` may leave its endpoints and client to discovery; one whose transport `url` is not https stays degraded with that reason. **Discovery organization, ruled B (ruling record 6545215904 on #26702)** - An `mcp` instance lists its tools at materialization, outside any run. While an `authorization_code` instance materializes, an ask that names no organization is answered as the connection with the **earliest `connected_at`** (ties by organization id); after the factory answers, such an ask is answered as D4 answers a run with none (the only connection, or `422` when there are several). Every dispatch still asks in its own run's organization. - That organization joins the `mcp` instance's reconcile signature, so when its connection is revoked, refused or connected again, the instance materializes again and lists as the next one. `rest` / `openapi` signatures are unchanged. **`@objectstack/connector-mcp`** - The plugin registers the provider with `{ credentialHandle: true }`. - With a handle, over `http`, every HTTP request of the MCP session goes through a fetch that asks the handle (`callWithBorrowedCredential`): a `401` refreshes once and is sent once more; a second `401` is the seam's `503` naming the instance. - Each organization a dispatch runs for opens its own MCP session with its own token; a session that failed to open is not kept; closing the instance closes every session. A dispatch with no organization goes through the session the tools were listed with. - A handle on a stdio transport, or beside a static credential or a request signer, is refused (a configuration fault). - `@objectstack/types` becomes a dependency; the vitest config aliases it to source (`check:test-source-alias`). **Docs**: `content/docs/automation/connectors.mdx`: the `mcp` provider leaves the "not served yet" paragraph and the failure-table row; the grant-bearing section gains the `mcp` paragraph (http only, per-organization sessions, the earliest-connection listing rule) and the MCP authorization flow; the revoke sentence no longer points at the discovery as future work. ## Tests - `service-automation/src/connector-mcp-authorization-door.test.ts` (14), over ObjectQL on SQLite and a local metadata / authorization / token server: DCR end to end (refresh with the kept client), reconnect reuse, an issued client secret never surfaced, the pre-registered form, `iss` mismatch refused and match accepted, no `S256`, issuer mismatch, resource mismatch, no registration endpoint, a server that does not answer (`503`), a non-https server not served, the `client_credentials` control, and **ruling B**: three organizations connect, the listing stays with the oldest, a dispatch uses its own organization, a run with none is `422`, and revoking the oldest re-materializes and lists as the next while two stay connected. - `service-automation/src/oauth2-grant/mcp-authorization.test.ts` (8): discovery order and the transport refusals. - `service-automation/src/oauth2-grant/grant-handle.test.ts`: four kept-client cases. - `connector-mcp/src/mcp-provider-credential-handle.test.ts` (8), over a real Streamable-HTTP server and the real SDK client: discovery request, per-organization sessions, 401 refresh-once, second 401, a failed session not kept, close, stdio and static refusals, the plugin opt-in. <details><summary>Ablations — 25, each red and each restored (<code>scripts/ablation-replace.mjs</code>, <code>git diff HEAD</code> empty after each)</summary> | # | Mutation | Red | |---|---|---| | b01 | drop the RFC 9207 `iss` check | the issuer-mismatch callback pin | | b02 | drop the `S256` requirement | the no-S256 pin | | b03 | drop the issuer equality check | the issuer-mismatch metadata pin | | b04 | drop the protected-resource `resource` check | the resource-mismatch pin | | b05 | accept a non-https server URL in discovery | the unit pin: refused before anything is fetched | | b05b | drop the non-https transport reason in the guard | the not-served pin | | b06 | accept a non-https authorization server | the unit pin: refused before its metadata is fetched | | b07 | drop `redirect: 'error'` on metadata fetches | the discovery-order unit case, which asserts every fetch refuses redirects | | b08 | drop the registered-code filter on a refused registration | the unit pin: only an RFC 7591 code, never the server's text | | b09 | drop the no-answer → upstream-unavailable mapping | the unit pin: no answer, `429` or `5xx` is operational and quotes nothing sent | | b10 | keep a declared client's secret in the kept client | the pre-registered-form door pin | | b11 | never reuse the kept client on reconnect | the reconnect-reuse pin | | b12 | refresh without reading the kept client | two grant-handle pins (kept endpoint and client; per-organization client) | | b13 | put the registered client in the connect log line | the issued-secret pin (never surfaced) | | c01 | every dispatch through the listing session | the per-organization session and refresh-once pins | | c02 | a get-only fetch (no refresh on 401) | the refresh-once pin | | c03 | accept a handle on stdio | the stdio refusal pin | | c04 | accept a handle beside a static credential | the exclusivity pin | | c05 | keep a session that failed to open | the failed-session pin | | c06 | close only the discovery session | the close pin | | c07 | plugin `credentialHandle: false` | the opt-in pin | | d01 | B: pass a no-organization ask through while materializing | ruling B (the re-listing as org_b fails) | | d02 | B: never settle (materialization answering stays on) | ruling B (a no-organization run resolves instead of `422`) | | d03 | B: drop the discovery organization from the mcp signature | ruling B (no re-materialization on the oldest's revoke) | | d04 | B: pick the latest connection | ruling B (re-materializes on each connect) | </details> ## Verification - Whole package suites before the last rebase (onto `630b4078`, which brought only comment changes to `plugin.ts` and `mcp-provider.ts` and a `connectors.mdx` hunk elsewhere on the page): service-automation 246 files / 3131 passed; connector-mcp 6 / 64; connector-rest 5 / 43; connector-openapi 7 / 89. - `pnpm --filter <pkg> run typecheck` (with `check:test-typecheck`): exit 0 for connector-mcp and service-automation. - eslint on the touched sources: exit 0. - `dispatch-gates --commands`: 104 families, all exit 0 after a whole-tree `turbo run build --filter='./packages/**'`; `--ran` reconcile: 104 derived, 104 run, 0 NOT-MEASURED, 0 unrun. - After the rebase, on head `5021bd3d`: both typechecks, the door and `oauth2-grant` suites, the connector-mcp suite, `check:doc-authoring`, `check:doc-anchors`, `check:docs-transcript-drift` and `check:doc-security-posture` re-run, all exit 0. ## Acceptance notes - **Size**: about 1,930 added lines, over the order's ~1,500. This PR is already the per-provider split (S2's second half). Roughly 1,000 of the lines are tests, and the rest is one flow (discovery, registration, the kept client and the provider) that does not split further without landing half of a connect. - **Contract review**: owed. `Clause-②: yes (widening)`, and `sys_connector_connection` gains a column (`registered_client`). - **Not measured live** against a vendor's MCP server (Notion, HubSpot); the flow is pinned against a local server that follows the RFCs. - **Unchanged**: the connection door handlers' routes and `capabilities.ts`; datasource lending of grant-bearing kinds is still refused with `422`; a revoke still does not call a revocation endpoint (none is read). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` is not touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; eslint passes on the touched sources. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset (`.changeset/26702-connector-mcp-oauth.md`), and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibwa6RkD7A2gK6rYRNT --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f91ab5a commit 7064615

21 files changed

Lines changed: 1935 additions & 79 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/connector-mcp': minor
3+
'@objectstack/service-automation': minor
4+
---
5+
6+
feat(connector-mcp): an OAuth-protected MCP server is connected through the MCP authorization flow and dispatched with each organization's token (ADR-0143 S2, part of #26702)
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: semantic
10+
11+
ADR-0143 lets a `provider: 'mcp'` instance over an http transport declare `auth: { type: 'oauth2', grant: 'authorization_code' }` and leave its endpoints, and its client, to discovery. Until now such an instance was held degraded, and the `mcp` provider did not ask the credential handle. Now:
12+
13+
- **The connect runs the MCP authorization flow** (`@objectstack/service-automation`). When an administrator begins a connect, the server reads the MCP server's protected-resource metadata (RFC 9728), then its authorization server's metadata (RFC 8414, or OpenID Connect discovery). The `issuer` must be the one the server named, and `S256` must be listed. A declared `clientId` is used as is (the pre-registered form). Otherwise a public client is registered (RFC 7591) for the deployment's redirect URI. Every authorization and token request carries the server's resource indicator (RFC 8707), PKCE stays on, and a callback that names another issuer is refused before its code is used (RFC 9207). Every URL on the way must be https (plain http only to a loopback host). No request follows a redirect.
14+
- **The connection keeps its client.** `sys_connector_connection` gains `registered_client`, an encrypted, masked field holding the discovered endpoints, the client id, and any client secret the registration issued (a declared client's secret stays behind its `credentialRef`). Refreshes use it, and a reconnect reuses it instead of registering again.
15+
- **The `mcp` provider asks the credential handle** (`@objectstack/connector-mcp`). The plugin registers it with `{ credentialHandle: true }`. Over http, every request of the MCP session goes through a fetch that asks the handle. A `401` refreshes once and is sent once more; a second `401` fails the call with the `503` naming the instance. Each organization a dispatch runs for gets its own MCP session and token. The tools are listed at materialization, outside any run, with the connection connected earliest (`connected_at`, ties by organization id), so an instance several organizations connected still lists; when that connection is revoked, refused or connected again, the instance materializes again and lists with the next one. A dispatch whose run names no organization is answered as before: from the only connection, or refused with `422` when there are several. A handle on a stdio transport, or beside a static credential, is refused.
16+
- An `oauth2` instance on `mcp` whose transport URL is not https is held degraded, and a `client_credentials` one still needs its declared endpoints.

‎content/docs/automation/connectors.mdx‎

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,9 @@ Config: **`transport`** (required) and **`include`** (optional tool-name
210210
allowlist — only the listed tools become actions):
211211

212212
- `{ kind: 'http', url, headers? }` — a remote MCP server over streamable
213-
HTTP. Resolved `auth` is folded into the request headers.
213+
HTTP. Resolved `auth` is folded into the request headers; a grant-bearing
214+
`auth` (`oauth2`, `app-credential`) is asked for on every request instead
215+
(see *Grant-bearing kinds* below).
214216
- `{ kind: 'stdio', command, args?, env? }` — a **local child process**,
215217
policy-gated (below). Credentials for a stdio server ride `transport.env`,
216218
not `auth`.
@@ -471,15 +473,29 @@ What the publish door checks, each refusal located at its key under `auth`:
471473
and a required `credentialRef`. An inline `appSecret` is refused by name.
472474

473475
**How the server serves them.** Both kinds are served through a
474-
**credential handle** the provider asks on every request. The built-in `rest`
475-
and `openapi` providers ask it; a provider says it does by registering with
476+
**credential handle** the provider asks on every request. The built-in `rest`,
477+
`openapi` and `mcp` providers ask it; a provider says it does by registering with
476478
`registerConnectorProvider(…, { credentialHandle: true })`. For an `openapi`
477479
instance the document's `security` decides only where the token is *not*
478480
sent: an operation whose effective `security` is `[]` is anonymous and never
479481
carries it, and a header or query parameter an `apiKey` scheme names is the
480482
platform's to fill, so it is left out of the action's input schema, as
481483
`Authorization` is.
482484

485+
An **`mcp`** instance carries a grant-bearing credential only over an `http`
486+
transport (a stdio server takes its credentials in `transport.env`; a handle
487+
on a stdio transport, or beside a static credential, fails the boot). Every
488+
HTTP request of its MCP session asks the handle. Each organization a dispatch
489+
runs for opens its own session with its own token, so organizations never
490+
share one. The tools are listed at materialization, outside any run, so the
491+
listing names no organization: on an `authorization_code` instance it uses
492+
the connection connected **earliest** (`connected_at`, ties by organization
493+
id), so an instance several organizations connected still lists. When that
494+
connection is revoked, refused or connected again, the instance materializes
495+
again and lists with the next one. A dispatch whose run names no organization
496+
is answered as below: from the only connection, refused when there are
497+
several.
498+
483499
An **`app-credential`** instance runs its vendor's exchange from the `appId`
484500
and the app secret its `credentialRef` names. The exchange is fixed per
485501
`vendor`, and nothing about it is authored:
@@ -538,7 +554,24 @@ a rotating refresh token is never spent twice.
538554
edited or moved there opens as nothing and its code is never exchanged.
539555
Write access to the cluster KV stays inside the platform's trust boundary,
540556
as it is for the cluster lock: such a writer can still delete a waiting
541-
connect. The redirect URI is the deployment's
557+
connect. On an `mcp` instance over `http` that leaves its endpoints or its
558+
client to discovery, the connect runs the **MCP authorization flow**: the
559+
server reads the MCP server's protected-resource metadata (RFC 9728), then
560+
its authorization server's metadata (RFC 8414, or OpenID Connect
561+
discovery). That metadata's `issuer` must be the one the MCP server named,
562+
and `S256` must be listed. A declared `clientId` is used as is; otherwise a
563+
public client is registered (RFC 7591) for the deployment's redirect URI, and
564+
an authorization server with no registration endpoint is refused, naming the
565+
`clientId` to declare. Every authorization and token request carries the MCP
566+
server's resource indicator (RFC 8707), and a callback that names another
567+
issuer is refused before its code is exchanged (RFC 9207). Every URL on the
568+
way must be `https://` (plain `http://` only to a loopback host), and no
569+
request follows a redirect. An MCP or authorization server that does not
570+
answer (or answers `429` / `5xx`) refuses the connect with `503`; metadata
571+
that is missing or fails a check above, with `400`. The discovered endpoints and client, including any
572+
client secret the registration issued, are kept encrypted in the
573+
connection's `registered_client`; refreshes use them, and a reconnect reuses
574+
them instead of registering again. The redirect URI is the deployment's
542575
(`OS_BASE_URL` or `OS_AUTH_URL` plus `/api/v1/automation/connectors/oauth/callback`,
543576
or the automation plugin's `connectorOAuthRedirectUri`), never the
544577
request's; register that URI with the vendor. The refresh token is kept
@@ -553,17 +586,19 @@ a rotating refresh token is never spent twice.
553586
stale one never overwrites a newer connect on any replica. A revoke deletes
554587
the stored connection only: the server does not revoke the refresh token at
555588
the vendor (RFC 7009), because no revocation endpoint is known for the
556-
instance yet — the auth declares none, and the discovery that would supply
557-
one is ADR-0143 S2. The refresh token stays valid at the vendor until it
589+
instance — the auth declares none, and the MCP authorization flow does not
590+
read one. The refresh token stays valid at the vendor until it
558591
expires or is revoked in the vendor's console; revoke it there too when the
559592
disconnect is a response to a leak.
560593

561594
What is not served yet is held **degraded** with a reason that names it, and
562595
never called without its credential: an `oauth2` or `app-credential`
563-
instance on a provider that does not ask the credential handle (the built-in
564-
`mcp` provider does not yet, nor does a plugin's provider registered without
565-
`{ credentialHandle: true }`), an `mcp` instance that left its endpoints to
566-
discovery, and an `oauth2`
596+
instance on a provider that does not ask the credential handle (a plugin's
597+
provider registered without `{ credentialHandle: true }`), an `oauth2`
598+
instance without its endpoints or client that the MCP authorization flow
599+
cannot discover them for (only an `authorization_code` instance on
600+
`provider: 'mcp'` over an `http` transport does), an `mcp` instance left to
601+
discovery whose transport `url` is not `https://`, and an `oauth2`
567602
instance whose `tokenUrl` or `authorizationUrl` is not `https://` (plain
568603
`http://` is accepted only to `localhost`, a `127.0.0.0/8` address or
569604
`[::1]` — not a `*.localhost` name, which the system resolver sends to DNS —
@@ -696,7 +731,7 @@ retry):
696731
|:---|:---|
697732
| `provider` names no installed factory | **Hard boot error** naming the entry, the provider, and the plugin that supplies it — add the executor to `plugins:` |
698733
| Invalid `providerConfig` (missing `baseUrl` / `spec` / `transport`, wrong shape) | **Hard boot error** from the provider factory |
699-
| `auth` is a grant-bearing kind (`oauth2`, `app-credential`) on a provider that does not ask the credential handle (the built-in `mcp` provider, for now) | **Not fatal**: the instance registers **degraded**, naming the kind, and the upstream is never called without its credential; a datasource borrowing it is refused with `422` |
734+
| `auth` is a grant-bearing kind (`oauth2`, `app-credential`) on a provider that does not ask the credential handle (a plugin's provider registered without `{ credentialHandle: true }`) | **Not fatal**: the instance registers **degraded**, naming the kind, and the upstream is never called without its credential; a datasource borrowing it is refused with `422` |
700735
| An `authorization_code` instance nobody connected, or whose grant the vendor refused | **Not fatal**: the instance registers **degraded**, "not connected" or "reconnect required" — connect it (`POST …/connectors/:name/connection`), and it materializes without a restart |
701736
| The token endpoint is unreachable or answers `5xx` / `429` | **Not fatal**: the dispatch fails `CONNECTOR_UPSTREAM_UNAVAILABLE` and is retried on the existing backoff; the connection stays connected |
702737
| `auth` is `signed` on a provider that does not say it applies the request signer | **Hard boot error** naming the instance, the scheme and the provider: its calls would go out unsigned — declare it through `rest` or `openapi` |

‎packages/connectors/connector-mcp/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
"dependencies": {
3030
"@modelcontextprotocol/sdk": "^1.30.1",
3131
"@objectstack/core": "workspace:*",
32-
"@objectstack/spec": "workspace:*"
32+
"@objectstack/spec": "workspace:*",
33+
"@objectstack/types": "workspace:*"
3334
},
3435
"devDependencies": {
3536
"@objectstack/service-automation": "workspace:*",

‎packages/connectors/connector-mcp/src/connector-mcp-plugin.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,18 @@ export interface ConnectorRegistrySurface {
2424
>,
2525
): void;
2626
unregisterConnector(name: string): void;
27-
registerConnectorProvider(providerKey: string, factory: ConnectorProviderFactory): void;
27+
/**
28+
* `options.credentialHandle: true` says the factory asks
29+
* `ConnectorProviderContext.credentialHandle` on every request, so the host
30+
* serves grant-bearing instances (`oauth2`, `app-credential`) through it
31+
* (ADR-0143 D4). An older host ignores the third argument and keeps
32+
* holding those instances degraded.
33+
*/
34+
registerConnectorProvider(
35+
providerKey: string,
36+
factory: ConnectorProviderFactory,
37+
options?: { readonly credentialHandle?: boolean },
38+
): void;
2839
}
2940

3041
/**
@@ -89,6 +100,8 @@ export class ConnectorMcpPlugin implements Plugin {
89100
clientFactory: this.options.clientFactory,
90101
declarativeStdio: this.options.declarativeStdio,
91102
}),
103+
// ADR-0143 D4 — an http transport asks the credential handle per request.
104+
{ credentialHandle: true },
92105
);
93106
ctx.logger.info("ConnectorMcpPlugin: registered 'mcp' connector provider");
94107
}

‎packages/connectors/connector-mcp/src/index.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@
1212
* doubles as an AI tool under ADR-0011.
1313
*
1414
* Open-source scope: the MCP client adapter (stdio + http transports),
15-
* `tools/list` → actions, `tools/call` dispatch, and operator-supplied static
16-
* credentials passed through the transport. A curated server registry, managed
17-
* secrets, per-tenant lifecycle, and sandboxed stdio execution are the
18-
* enterprise tier (ADR-0024 §4).
15+
* `tools/list` → actions, `tools/call` dispatch, operator-supplied static
16+
* credentials passed through the transport, and — over http — an OAuth-protected
17+
* server's per-dispatch token through the host's credential handle, one MCP
18+
* session per organization (ADR-0143 D4; the host runs the MCP authorization
19+
* flow when an administrator connects the instance). A curated server
20+
* registry, sandboxed stdio execution and the rest of ADR-0024 §4 stay the
21+
* enterprise tier.
1922
*/
2023

2124
export {

‎packages/connectors/connector-mcp/src/mcp-connector.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ export type McpTransport =
6161
url: string;
6262
/** Headers sent on every request — carries credentials (e.g. a bearer token). */
6363
headers?: Record<string, string>;
64+
/**
65+
* The fetch every request of the transport goes through, when the
66+
* credential is runtime state rather than a header: the `mcp`
67+
* provider's credential handle (ADR-0143 D4) applies the token
68+
* per request through it. Default the global `fetch`.
69+
*/
70+
fetch?: typeof fetch;
6471
};
6572

6673
/** A tool as advertised by an MCP server's `tools/list`. */
@@ -111,6 +118,14 @@ export interface McpConnectorOptions {
111118
* configured transport and returns a connected {@link McpClientLike}.
112119
*/
113120
clientFactory?: (transport: McpTransport, clientInfo: { name: string; version: string }) => Promise<McpClientLike>;
121+
/**
122+
* The client a tool call goes to, chosen per call from the dispatch's
123+
* context; `undefined` (or no member) sends it through the client the
124+
* tools were listed with. The `mcp` provider answers one client per
125+
* organization when the instance's credential is a per-organization
126+
* connection (ADR-0143 D4, Q1).
127+
*/
128+
clientFor?: (ctx: unknown) => McpClientLike | undefined | Promise<McpClientLike | undefined>;
114129
}
115130

116131
/**
@@ -127,7 +142,7 @@ export interface McpConnectorBundle {
127142
close(): Promise<void>;
128143
}
129144

130-
const DEFAULT_CLIENT_INFO = { name: 'objectstack-connector-mcp', version: '1.0.0' } as const;
145+
export const DEFAULT_MCP_CLIENT_INFO = { name: 'objectstack-connector-mcp', version: '1.0.0' } as const;
131146

132147
/** Slugify a label into a valid connector `name` (`/^[a-z_][a-z0-9_]*$/`). */
133148
function slugify(input: string): string {
@@ -187,7 +202,7 @@ export const MCP_TOOLS_LIST_MAX_PAGES = 100;
187202
* The default {@link McpClientLike} — lazily imports the official MCP SDK so it
188203
* is only loaded when a real connection is made (tests inject their own client).
189204
*/
190-
async function defaultClientFactory(
205+
export async function defaultMcpClientFactory(
191206
transport: McpTransport,
192207
clientInfo: { name: string; version: string },
193208
): Promise<McpClientLike> {
@@ -212,6 +227,7 @@ async function defaultClientFactory(
212227
await client.connect(
213228
new StreamableHTTPClientTransport(new URL(transport.url), {
214229
requestInit: transport.headers ? { headers: transport.headers } : undefined,
230+
...(transport.fetch ? { fetch: transport.fetch } : {}),
215231
}),
216232
);
217233
}
@@ -250,8 +266,8 @@ async function defaultClientFactory(
250266
* tear it down.
251267
*/
252268
export async function createMcpConnector(opts: McpConnectorOptions): Promise<McpConnectorBundle> {
253-
const clientInfo = opts.clientInfo ?? DEFAULT_CLIENT_INFO;
254-
const factory = opts.clientFactory ?? defaultClientFactory;
269+
const clientInfo = opts.clientInfo ?? DEFAULT_MCP_CLIENT_INFO;
270+
const factory = opts.clientFactory ?? defaultMcpClientFactory;
255271

256272
const client = await factory(opts.transport, clientInfo);
257273

@@ -306,7 +322,10 @@ export async function createMcpConnector(opts: McpConnectorOptions): Promise<Mcp
306322
};
307323

308324
for (const tool of selected) {
309-
handlers[tool.name] = async (input) => normalizeResult(await client.callTool(tool.name, input));
325+
handlers[tool.name] = async (input, ctx) => {
326+
const target = (opts.clientFor ? await opts.clientFor(ctx) : undefined) ?? client;
327+
return normalizeResult(await target.callTool(tool.name, input));
328+
};
310329
}
311330

312331
return {

0 commit comments

Comments
 (0)