@abgov/adsp-sdk-mcp-server 1.37.0 → 1.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -22
- package/assets/docs/services/event-service.md +3 -1
- package/package.json +3 -1
- package/provenance.json +4 -4
- package/src/auth.d.ts +34 -0
- package/src/auth.js +218 -0
- package/src/auth.js.map +1 -0
- package/src/config.d.ts +10 -0
- package/src/config.js +36 -0
- package/src/config.js.map +1 -1
- package/src/guards.js +2 -2
- package/src/guards.js.map +1 -1
- package/src/hosted.d.ts +1 -1
- package/src/hosted.js +1 -1
- package/src/hosted.js.map +1 -1
- package/src/http.d.ts +1 -1
- package/src/http.js +25 -3
- package/src/http.js.map +1 -1
- package/src/instructions.d.ts +2 -5
- package/src/instructions.js +17 -4
- package/src/instructions.js.map +1 -1
- package/src/main.js +1 -1
- package/src/main.js.map +1 -1
- package/src/metrics.d.ts +1 -1
- package/src/server.d.ts +8 -0
- package/src/server.js +35 -4
- package/src/server.js.map +1 -1
- package/src/tools/registerConfigurationSchemaTool.js +13 -4
- package/src/tools/registerConfigurationSchemaTool.js.map +1 -1
- package/src/tools/registerServiceRolesTool.js +13 -4
- package/src/tools/registerServiceRolesTool.js.map +1 -1
- package/src/tools/types.d.ts +9 -0
- package/src/tools/types.js +4 -0
- package/src/tools/types.js.map +1 -1
- package/src/tools/upstreamErrors.d.ts +1 -0
- package/src/tools/upstreamErrors.js +2 -0
- package/src/tools/upstreamErrors.js.map +1 -1
package/README.md
CHANGED
|
@@ -114,16 +114,28 @@ Add it to your MCP client's server config, run via `npx`:
|
|
|
114
114
|
### HTTP transport
|
|
115
115
|
|
|
116
116
|
To host the server instead of running it per user, start it with `MCP_TRANSPORT=http`. It serves Streamable HTTP
|
|
117
|
-
|
|
117
|
+
on two endpoints, with a liveness check at `GET /health` and a readiness check at `GET /ready`:
|
|
118
|
+
|
|
119
|
+
| Endpoint | Sign-in | Tools |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| `POST /mcp` | Never asked for; a token sent here is ignored | The 10 tools that answer from bundled content. `list_service_roles` and `get_service_configuration_schema` aren't listed, and calling them answers with an error saying to sign in at `/mcp/<tenant realm>` |
|
|
122
|
+
| `POST /mcp/<tenant realm>` | Required for that tenant realm (see [Signing in](#signing-in)) | All 12 |
|
|
123
|
+
|
|
124
|
+
Without the three sign-in settings below, the server serves only `/mcp`. There is no way to call the live tools
|
|
125
|
+
without signing in: anyone who can't sign in, and needs them, runs the server locally over stdio, as in
|
|
126
|
+
[Usage](#usage).
|
|
118
127
|
|
|
119
128
|
| Variable | Default | Purpose |
|
|
120
129
|
|---|---|---|
|
|
121
130
|
| `MCP_TRANSPORT` | `stdio` | `http` to serve HTTP |
|
|
122
131
|
| `PORT` | `3000` | Port to listen on |
|
|
123
|
-
| `
|
|
124
|
-
| `
|
|
132
|
+
| `MCP_PUBLIC_URL` | unset | The server's external base URL, for example `https://adsp-sdk-mcp.example`. Used in the sign-in metadata and the `WWW-Authenticate` header, never taken from request headers |
|
|
133
|
+
| `ADSP_ACCESS_SERVICE_URL` | unset | Keycloak base URL. A realm's issuer is `<url>/auth/realms/<realm>` and its signing keys are read from there |
|
|
134
|
+
| `ADSP_DIRECTORY_SERVICE_URL` | unset | Directory service the live tools use to find ADSP services. Set all three sign-in settings to serve `/mcp/<tenant realm>` |
|
|
135
|
+
| `CORS_ORIGIN` | unset | Comma-separated browser origins allowed to call `/mcp` and `/mcp/<tenant realm>`, for example `https://a.example,https://b.example`. Unset allows none; `*` allows any (not for hosted use) |
|
|
136
|
+
| `MCP_MAX_IN_FLIGHT` | `64` | Requests handled at once per process, on each endpoint: `POST /mcp`, and signed-in `POST /mcp/<tenant realm>`. Each endpoint has its own slots, so requests without a token can't take the ones signed-in callers need |
|
|
125
137
|
| `MCP_IN_FLIGHT_WAIT_MS` | `1000` | How long a request waits for a free slot before getting `503`. Also how long a live tool waits for a free upstream slot |
|
|
126
|
-
| `MCP_RATE_LIMIT_PER_MINUTE` | `1200` | `POST /mcp` requests allowed per client IP per minute, per process. `0` turns the limit off |
|
|
138
|
+
| `MCP_RATE_LIMIT_PER_MINUTE` | `1200` | `POST /mcp` and `POST /mcp/<tenant realm>` requests allowed per client IP per minute, per process, counted together. `0` turns the limit off |
|
|
127
139
|
| `MCP_LIVE_TOOL_MAX_CONCURRENT` | `8` | Live-tool calls to ADSP running at once per process, across both live tools |
|
|
128
140
|
| `MCP_SHUTDOWN_DELAY_MS` | `5000` | After a shutdown signal, how long to keep serving with `/ready` failing, so the router stops sending traffic first |
|
|
129
141
|
| `MCP_SHUTDOWN_TIMEOUT_MS` | `30000` | Hard deadline from the signal to exit, even if a request is still running. Must be longer than the delay |
|
|
@@ -131,16 +143,64 @@ at `POST /mcp`, with a liveness check at `GET /health` and a readiness check at
|
|
|
131
143
|
| `OTEL_EXPORTER_OTLP_ENDPOINT` | unset | OTLP/HTTP collector base URL. When set, metrics are exported to `<endpoint>/v1/metrics` |
|
|
132
144
|
| `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | Metric export interval, in milliseconds |
|
|
133
145
|
|
|
134
|
-
An invalid value for one of the `MCP_*` numbers,
|
|
146
|
+
An invalid value for one of the `MCP_*` numbers, `*` mixed with origins in `CORS_ORIGIN`, some but not all of the
|
|
147
|
+
three sign-in settings, or a sign-in URL that isn't `https` (plain `http` is allowed only for `localhost` and `127.0.0.1`) stops the server at
|
|
135
148
|
startup with an error naming the variable.
|
|
136
149
|
|
|
137
|
-
HTTP mode is stateless: each `POST
|
|
138
|
-
and nothing is kept between requests. The response carries no `Mcp-Session-Id`, so any replica can
|
|
139
|
-
and an idle client never loses its session. `GET
|
|
140
|
-
there is no stream to open and no session to delete.
|
|
150
|
+
HTTP mode is stateless: each `POST` to either endpoint gets its own MCP server, the response is JSON (the server
|
|
151
|
+
never streams), and nothing is kept between requests. The response carries no `Mcp-Session-Id`, so any replica can
|
|
152
|
+
serve any request and an idle client never loses its session. `GET` and `DELETE` on both endpoints return
|
|
153
|
+
`405` with `Allow: POST`, because there is no stream to open and no session to delete.
|
|
141
154
|
|
|
142
155
|
`SESSION_TTL_MINUTES` has been removed and is ignored: there are no sessions to expire.
|
|
143
156
|
|
|
157
|
+
#### Signing in
|
|
158
|
+
|
|
159
|
+
`/mcp/<tenant realm>` is an OAuth protected resource; plain `/mcp` never asks for a sign-in.
|
|
160
|
+
Each tenant realm is its own authorization server, so the realm is part of the URL: a client connects to
|
|
161
|
+
`<MCP_PUBLIC_URL>/mcp/<tenant realm>` and signs in to that realm with the public client `adsp-mcp` (PKCE, no secret).
|
|
162
|
+
|
|
163
|
+
- A request without a token gets `401` with
|
|
164
|
+
`WWW-Authenticate: Bearer resource_metadata="<MCP_PUBLIC_URL>/.well-known/oauth-protected-resource/mcp/<realm>"`.
|
|
165
|
+
That document ([RFC 9728](https://www.rfc-editor.org/rfc/rfc9728)) names the realm as the only authorization
|
|
166
|
+
server, and the client finds Keycloak through `<issuer>/.well-known/openid-configuration`.
|
|
167
|
+
- A token is accepted only if it is signed by that realm (RS256), its issuer is exactly
|
|
168
|
+
`<ADSP_ACCESS_SERVICE_URL>/auth/realms/<realm>`, its audience includes `urn:ads:platform:adsp-sdk-mcp-server`, and
|
|
169
|
+
it hasn't expired (30 s clock tolerance). Anything else gets `401` with `error="invalid_token"`. A realm's token is
|
|
170
|
+
never accepted on another realm's URL.
|
|
171
|
+
- The server keeps no secret. It verifies tokens with each realm's public signing keys, refreshed after 10 minutes.
|
|
172
|
+
A token with a key id the server hasn't seen triggers a refresh at most once every 30 s, so rotated keys are
|
|
173
|
+
picked up and junk key ids can't drive traffic. If a refresh fails, the realm keeps working with its last keys.
|
|
174
|
+
- If a realm's keys have never been fetched and can't be within 5 s, requests for that realm get `503` with
|
|
175
|
+
`Retry-After` for the next 60 s. A realm that doesn't exist looks the same to the server, so a mistyped realm in the
|
|
176
|
+
URL also gets `503`. Key fetches are capped at 20 a minute across all realms per process, so made-up realm names
|
|
177
|
+
can't make the server send unbounded traffic to Keycloak, and they never push out a realm whose keys are known.
|
|
178
|
+
After a restart, each replica can therefore start verifying at most 20 new realms a minute.
|
|
179
|
+
- Every request is checked on its own token, and nothing from one request is kept for the next. Tokens are never
|
|
180
|
+
logged or written to disk.
|
|
181
|
+
|
|
182
|
+
The live tools (`list_service_roles` and `get_service_configuration_schema`) call ADSP **as the signed-in caller**,
|
|
183
|
+
with the caller's token and `ADSP_DIRECTORY_SERVICE_URL`. The host needs no `adsp-cli` login, `ADSP_CLIENT_ID` or
|
|
184
|
+
`ADSP_CLIENT_SECRET`. If ADSP rejects the token, the tool answers "Your sign-in was rejected or has expired. Sign in
|
|
185
|
+
again from your MCP client." The tool descriptions still mention `adsp-cli login`, which applies only to stdio.
|
|
186
|
+
|
|
187
|
+
A realm can sign in only if it has the `adsp-mcp` client. New tenant realms get it when they're created; existing
|
|
188
|
+
realms need it added.
|
|
189
|
+
|
|
190
|
+
Connecting each supported client, with `<url>` standing for `<MCP_PUBLIC_URL>/mcp/<tenant realm>`:
|
|
191
|
+
|
|
192
|
+
- **Claude Code:** `claude mcp add --transport http --client-id adsp-mcp --callback-port 33419 adsp-sdk <url>`, then
|
|
193
|
+
`/mcp` in Claude Code to sign in. Without `--callback-port` it picks a random port that isn't registered.
|
|
194
|
+
- **VS Code (GitHub Copilot):** add the server as type `http` with `<url>`. When VS Code says the server doesn't
|
|
195
|
+
support dynamic client registration, enter `adsp-mcp` as the client id and leave the secret empty. VS Code
|
|
196
|
+
receives the sign-in on port 33418, which must be free.
|
|
197
|
+
- **Cursor:** in `mcp.json`, `"adsp-sdk": { "url": "<url>", "auth": { "CLIENT_ID": "adsp-mcp" } }`.
|
|
198
|
+
- **MCP Inspector:** transport Streamable HTTP, URL `<url>`, and client id `adsp-mcp` in the authentication settings.
|
|
199
|
+
|
|
200
|
+
Known client issues reported upstream: some Claude Code versions store `--client-id` under the wrong key, VS Code
|
|
201
|
+
fails to sign in when port 33418 is busy, and Cursor's redirect has changed between versions. If sign-in fails with
|
|
202
|
+
a redirect error, the client's redirect is probably not one the `adsp-mcp` client allows.
|
|
203
|
+
|
|
144
204
|
#### Health and shutdown
|
|
145
205
|
|
|
146
206
|
- `GET /health` is liveness: it answers `200` while the process is up, including during the shutdown delay, so a pod
|
|
@@ -161,16 +221,20 @@ than it takes the router to stop sending traffic to a pod that fails readiness.
|
|
|
161
221
|
|
|
162
222
|
#### Overload guards
|
|
163
223
|
|
|
164
|
-
`POST /mcp`
|
|
165
|
-
|
|
224
|
+
`POST /mcp` and `POST /mcp/<tenant realm>` pass these checks in order, and `POST /mcp` skips the sign-in step.
|
|
225
|
+
`GET /health` skips all of them. Every rejection is a
|
|
226
|
+
JSON-RPC error body (`code: -32000`) and is counted in `mcp.requests.rejected`.
|
|
166
227
|
|
|
167
228
|
1. **Origin.** A request with an `Origin` header not in `CORS_ORIGIN` gets `403` (`Origin not allowed`), as the MCP
|
|
168
229
|
specification requires. `Origin: null` is never allowed. A request without an `Origin` header, which is what
|
|
169
230
|
non-browser clients such as agent-service and the MCP SDK send, passes. `Access-Control-Allow-Origin` is sent only
|
|
170
231
|
for an allowed origin.
|
|
171
232
|
2. **Rate limit.** Over `MCP_RATE_LIMIT_PER_MINUTE` from one client IP, a request gets `429` with `Retry-After`
|
|
172
|
-
(`Rate limit exceeded`).
|
|
173
|
-
3. **
|
|
233
|
+
(`Rate limit exceeded`). This runs before sign-in, so requests with bad tokens count too.
|
|
234
|
+
3. **Sign-in.** A realm name that isn't letters, digits, `-` and `_` (up to 64) gets `404`, a missing or invalid
|
|
235
|
+
token `401`, and unavailable signing keys `503` (see [Signing in](#signing-in)). Requests that fail here never take
|
|
236
|
+
an in-flight slot.
|
|
237
|
+
4. **In-flight cap.** With `MCP_MAX_IN_FLIGHT` requests already running on the same endpoint, a request waits up to
|
|
174
238
|
`MCP_IN_FLIGHT_WAIT_MS` for a slot, so a short burst completes. A request still waiting after that, or arriving
|
|
175
239
|
when as many requests are already waiting as `MCP_MAX_IN_FLIGHT`, gets `503` with `Retry-After: 1`
|
|
176
240
|
(`Server busy`). Requests already running are never affected. A request is admitted before its body arrives, so
|
|
@@ -185,10 +249,10 @@ place and never calls ADSP. This applies in stdio mode too.
|
|
|
185
249
|
Things to know when sizing and tuning these:
|
|
186
250
|
|
|
187
251
|
- **The limits are per process.** With N replicas, the cluster takes about N times each limit.
|
|
188
|
-
- **The rate limit is per client IP
|
|
189
|
-
so is any group of users behind one NAT or proxy. Connecting and calling one
|
|
190
|
-
allows about 400 such client sessions a minute from one IP. Retune it once the
|
|
191
|
-
reach the pod.
|
|
252
|
+
- **The rate limit is per client IP, not per signed-in user,** because it runs before the token is checked. Every
|
|
253
|
+
agent-service pod is one client, and so is any group of users behind one NAT or proxy. Connecting and calling one
|
|
254
|
+
tool is 3 `POST`s, so the default allows about 400 such client sessions a minute from one IP. Retune it once the
|
|
255
|
+
deployment shows which client IPs reach the pod.
|
|
192
256
|
- **Clients don't retry.** Measured locally with `MCP_MAX_IN_FLIGHT=2` and both slots held:
|
|
193
257
|
|
|
194
258
|
| Client | Over the cap for longer than `MCP_IN_FLIGHT_WAIT_MS` | Over the cap briefly (`MCP_IN_FLIGHT_WAIT_MS=3000`, slots freed after 0.5 s) |
|
|
@@ -207,9 +271,9 @@ OpenTelemetry SDK isn't loaded. Stdio mode never exports metrics.
|
|
|
207
271
|
|
|
208
272
|
| Name | Kind | Unit | Labels | Meaning |
|
|
209
273
|
|---|---|---|---|---|
|
|
210
|
-
| `mcp.requests.in_flight` | UpDownCounter | `{request}` | none | `POST /mcp` requests admitted by the in-flight cap and not yet answered (waiting requests aren't counted) |
|
|
211
|
-
| `mcp.requests.rejected` | Counter | `{request}` | `reason` | Requests or tool calls refused by an overload guard |
|
|
212
|
-
| `mcp.request.duration` | Histogram | `s` | `mcp.method.name`, and `http.response.status_code` or `error.type=aborted` | Time to answer a `POST /mcp` request, or until the client disconnected |
|
|
274
|
+
| `mcp.requests.in_flight` | UpDownCounter | `{request}` | none | `POST /mcp` and `POST /mcp/<tenant realm>` requests admitted by the in-flight cap and not yet answered (waiting requests aren't counted) |
|
|
275
|
+
| `mcp.requests.rejected` | Counter | `{request}` | `reason` | Requests or tool calls refused by an overload guard or by sign-in |
|
|
276
|
+
| `mcp.request.duration` | Histogram | `s` | `mcp.method.name`, and `http.response.status_code` or `error.type=aborted` | Time to answer a `POST /mcp` request, or a `POST /mcp/<tenant realm>` request that passed sign-in, or until the client disconnected |
|
|
213
277
|
| `mcp.tool.duration` | Histogram | `s` | `mcp.tool.name`, `error.type` (absent on success) | Time to run a tool call |
|
|
214
278
|
| `mcp.live_tool.upstream.errors` | Counter | `{error}` | `mcp.tool.name`, `error.type` | Failed ADSP calls from `list_service_roles` and `get_service_configuration_schema` |
|
|
215
279
|
| `nodejs.eventloop.delay.p50`, `.p99`, `.max` | Gauge | `s` | none | Event-loop delay since the previous export |
|
|
@@ -219,7 +283,7 @@ OpenTelemetry SDK isn't loaded. Stdio mode never exports metrics.
|
|
|
219
283
|
|
|
220
284
|
Every label takes a value from a fixed set:
|
|
221
285
|
|
|
222
|
-
- `mcp.tool.name`: one of the
|
|
286
|
+
- `mcp.tool.name`: one of the twelve tool names, or `unknown` for any name the server doesn't have.
|
|
223
287
|
- `mcp.method.name`: an MCP method such as `initialize`, `tools/list` or `tools/call`; `other` for any other method;
|
|
224
288
|
`batch` for a JSON-RPC batch; `unparsed` when the body wasn't valid JSON-RPC or was too large.
|
|
225
289
|
- `error.type` on `mcp.request.duration`: `aborted` when the client disconnected before the response was written; the
|
|
@@ -229,7 +293,9 @@ Every label takes a value from a fixed set:
|
|
|
229
293
|
- `error.type` on `mcp.live_tool.upstream.errors`: `http_4xx`, `http_5xx`, `network`, `not_in_directory`,
|
|
230
294
|
`not_authenticated` or `other`. `not_authenticated` covers both a missing `adsp-cli` login and a failed token
|
|
231
295
|
request, which `adsp-cli` reports the same way.
|
|
232
|
-
- `reason` on `mcp.requests.rejected`: `in_flight_cap`, `rate_limit`, `origin`
|
|
296
|
+
- `reason` on `mcp.requests.rejected`: `in_flight_cap`, `rate_limit`, `origin`, `live_tool_cap`, `auth` (a `401`
|
|
297
|
+
for an invalid token; a request with no token isn't counted, because every client's first request has none) or
|
|
298
|
+
`auth_unavailable` (a `503` because a realm's signing keys couldn't be fetched).
|
|
233
299
|
|
|
234
300
|
### Using the live tools
|
|
235
301
|
|
|
@@ -61,7 +61,9 @@ Change sets are not captured for `event-definition.created`, since the new defin
|
|
|
61
61
|
|
|
62
62
|
Sending domain events (`POST /event/v1/events`) and reading or querying definitions and the event log are not audited; sent events are recorded in the [event log](#event-log). Event definitions written directly to the [configuration service](configuration-service.md) under `platform:event-service`, including platform definitions registered by services on startup, bypass the event service and are not recorded here.
|
|
63
63
|
|
|
64
|
-
Audit failures are logged and do not prevent the definition change. The event service account requires the `audit-writer` role of `urn:ads:platform:audit-service`.
|
|
64
|
+
Audit failures are logged and do not prevent the definition change. The event service account requires the `audit-writer` role of `urn:ads:platform:audit-service`.
|
|
65
|
+
|
|
66
|
+
Audit recording is on by default. Set the environment variable `EVENT_AUDIT_ENABLED=false` on event service to turn off the event definition records, or `true` to turn them on regardless of the SDK `AUDIT_ENABLED` variable, which applies when `EVENT_AUDIT_ENABLED` is not set. `EVENT_AUDIT_ENABLED` does not affect the [access service audit](#access-service-audit) records, which have their own `ACCESS_AUDIT_ENABLED` variable; `AUDIT_ENABLED=false` turns off both when neither variable is set. The action catalog is still registered while recording is off, so turning it back on needs only a restart. See [turn audit recording off](audit-service.md#turn-audit-recording-off).
|
|
65
67
|
|
|
66
68
|
## Concepts
|
|
67
69
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abgov/adsp-sdk-mcp-server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.39.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "Government of Alberta - MCP server for ADSP documentation and Node SDK reference lookup.",
|
|
6
6
|
"repository": "https://github.com/GovAlta/adsp-monorepo",
|
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
"@opentelemetry/sdk-metrics": "2.10.0",
|
|
17
17
|
"express": "^4.21.0",
|
|
18
18
|
"express-rate-limit": "^7.1.4",
|
|
19
|
+
"jsonwebtoken": "^9.0.3",
|
|
20
|
+
"jwks-rsa": "^2.1.4",
|
|
19
21
|
"tslib": "^2.3.0",
|
|
20
22
|
"zod": "^4.6.7"
|
|
21
23
|
},
|
package/provenance.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"kind": "release",
|
|
3
|
-
"builtAt": "2026-11-
|
|
4
|
-
"sourceCommit": "
|
|
5
|
-
"latestRelease": "1.
|
|
6
|
-
"docsCommit": "
|
|
3
|
+
"builtAt": "2026-11-18T21:13:19.558Z",
|
|
4
|
+
"sourceCommit": "329e321c3e42719df39c4fb4dbae0abdc5b9604c",
|
|
5
|
+
"latestRelease": "1.38.0",
|
|
6
|
+
"docsCommit": "1dd532f1f2692b5648143264734a12cd254e19a6",
|
|
7
7
|
"sdk": {
|
|
8
8
|
"version": "2.36.1",
|
|
9
9
|
"commit": "dd58a2b854c4406b42c0604dba3fa4b941038d6c",
|
package/src/auth.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
|
|
2
|
+
import type * as express from 'express';
|
|
3
|
+
export declare const MCP_AUDIENCE = "urn:ads:platform:adsp-sdk-mcp-server";
|
|
4
|
+
/** New realms are UUIDs; older ones are simple names. Anything else never reaches a URL. */
|
|
5
|
+
export declare const REALM_PATTERN: RegExp;
|
|
6
|
+
export declare class InvalidTokenError extends Error {
|
|
7
|
+
}
|
|
8
|
+
export declare class AuthUnavailableError extends Error {
|
|
9
|
+
readonly retryAfterSeconds: number;
|
|
10
|
+
constructor(retryAfterSeconds: number);
|
|
11
|
+
}
|
|
12
|
+
export interface TokenVerifierOptions {
|
|
13
|
+
accessServiceUrl: string;
|
|
14
|
+
maxRealms?: number;
|
|
15
|
+
negativeCacheMs?: number;
|
|
16
|
+
maxFetchesPerMinute?: number;
|
|
17
|
+
fetchTimeoutMs?: number;
|
|
18
|
+
keyCacheMs?: number;
|
|
19
|
+
refetchMinMs?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface TokenVerifier {
|
|
22
|
+
verify(realm: string, token: string): Promise<AuthInfo>;
|
|
23
|
+
}
|
|
24
|
+
export declare function createTokenVerifier({ accessServiceUrl, maxRealms, negativeCacheMs, maxFetchesPerMinute, fetchTimeoutMs, keyCacheMs, refetchMinMs, }: TokenVerifierOptions): TokenVerifier;
|
|
25
|
+
/** Expects the realm in `req.params.tenantRealm`; sets `req.auth` for the MCP transport. */
|
|
26
|
+
export declare function createAuthMiddleware({ verifier, publicUrl, }: {
|
|
27
|
+
verifier: TokenVerifier;
|
|
28
|
+
publicUrl: string;
|
|
29
|
+
}): express.RequestHandler;
|
|
30
|
+
/** RFC 9728 protected-resource metadata, built only from configuration, never from request headers. */
|
|
31
|
+
export declare function createProtectedResourceMetadataHandler({ publicUrl, accessServiceUrl, }: {
|
|
32
|
+
publicUrl: string;
|
|
33
|
+
accessServiceUrl: string;
|
|
34
|
+
}): express.RequestHandler;
|
package/src/auth.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AuthUnavailableError = exports.InvalidTokenError = exports.REALM_PATTERN = exports.MCP_AUDIENCE = void 0;
|
|
4
|
+
exports.createTokenVerifier = createTokenVerifier;
|
|
5
|
+
exports.createAuthMiddleware = createAuthMiddleware;
|
|
6
|
+
exports.createProtectedResourceMetadataHandler = createProtectedResourceMetadataHandler;
|
|
7
|
+
const jsonwebtoken_1 = require("jsonwebtoken");
|
|
8
|
+
const jwks_rsa_1 = require("jwks-rsa");
|
|
9
|
+
const guards_1 = require("./guards");
|
|
10
|
+
const metrics_1 = require("./metrics");
|
|
11
|
+
exports.MCP_AUDIENCE = 'urn:ads:platform:adsp-sdk-mcp-server';
|
|
12
|
+
/** New realms are UUIDs; older ones are simple names. Anything else never reaches a URL. */
|
|
13
|
+
exports.REALM_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
14
|
+
const FETCH_WINDOW_MS = 60_000;
|
|
15
|
+
const KEY_CACHE_MS = 10 * 60_000;
|
|
16
|
+
const CLOCK_TOLERANCE_SECONDS = 30;
|
|
17
|
+
const REFETCH_MIN_MS = 30_000;
|
|
18
|
+
/** A token without a kid can only match a realm that publishes a single key. */
|
|
19
|
+
function keyById({ keys }, kid) {
|
|
20
|
+
if (kid !== undefined) {
|
|
21
|
+
return keys.get(kid);
|
|
22
|
+
}
|
|
23
|
+
return keys.size === 1 ? keys.values().next().value : undefined;
|
|
24
|
+
}
|
|
25
|
+
class InvalidTokenError extends Error {
|
|
26
|
+
}
|
|
27
|
+
exports.InvalidTokenError = InvalidTokenError;
|
|
28
|
+
class AuthUnavailableError extends Error {
|
|
29
|
+
retryAfterSeconds;
|
|
30
|
+
constructor(retryAfterSeconds) {
|
|
31
|
+
super('Sign-in keys are unavailable');
|
|
32
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.AuthUnavailableError = AuthUnavailableError;
|
|
36
|
+
function retryAfter(untilMs) {
|
|
37
|
+
return Math.max(1, Math.ceil((untilMs - Date.now()) / 1000));
|
|
38
|
+
}
|
|
39
|
+
function createTokenVerifier({ accessServiceUrl, maxRealms = 100, negativeCacheMs = 60_000, maxFetchesPerMinute = 20, fetchTimeoutMs = 5_000, keyCacheMs = KEY_CACHE_MS, refetchMinMs = REFETCH_MIN_MS, }) {
|
|
40
|
+
// Insertion-ordered maps used as LRUs, so a stream of made-up realm names can't grow memory without bound.
|
|
41
|
+
// Only realms whose keys were fetched successfully enter realmKeys, so made-up realms can't evict real ones.
|
|
42
|
+
const realmKeys = new Map();
|
|
43
|
+
const unavailableUntil = new Map();
|
|
44
|
+
const pendingFetches = new Map();
|
|
45
|
+
const fetchTimes = [];
|
|
46
|
+
const issuerFor = (realm) => `${accessServiceUrl}/auth/realms/${realm}`;
|
|
47
|
+
function remember(map, key, value) {
|
|
48
|
+
map.delete(key);
|
|
49
|
+
map.set(key, value);
|
|
50
|
+
if (map.size > maxRealms) {
|
|
51
|
+
map.delete(map.keys().next().value);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function fetchJwks(uri) {
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
while (fetchTimes.length > 0 && fetchTimes[0] <= now - FETCH_WINDOW_MS) {
|
|
57
|
+
fetchTimes.shift();
|
|
58
|
+
}
|
|
59
|
+
if (fetchTimes.length >= maxFetchesPerMinute) {
|
|
60
|
+
throw new AuthUnavailableError(retryAfter(fetchTimes[0] + FETCH_WINDOW_MS));
|
|
61
|
+
}
|
|
62
|
+
fetchTimes.push(now);
|
|
63
|
+
const response = await fetch(uri, { signal: AbortSignal.timeout(fetchTimeoutMs) });
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
throw new Error(`JWKS request failed with status ${response.status}`);
|
|
66
|
+
}
|
|
67
|
+
// JSON.parse rather than response.json(): jose rejects objects built in another realm (e.g. Jest's sandbox).
|
|
68
|
+
return JSON.parse(await response.text());
|
|
69
|
+
}
|
|
70
|
+
function refreshKeys(realm) {
|
|
71
|
+
const pending = pendingFetches.get(realm);
|
|
72
|
+
if (pending) {
|
|
73
|
+
return pending;
|
|
74
|
+
}
|
|
75
|
+
const client = new jwks_rsa_1.JwksClient({ jwksUri: `${issuerFor(realm)}/protocol/openid-connect/certs`, fetcher: fetchJwks });
|
|
76
|
+
const fetching = client
|
|
77
|
+
.getSigningKeys()
|
|
78
|
+
.then((signingKeys) => {
|
|
79
|
+
const fresh = { keys: new Map(signingKeys.map((key) => [key.kid, key.getPublicKey()])), fetchedAt: Date.now() };
|
|
80
|
+
remember(realmKeys, realm, fresh);
|
|
81
|
+
unavailableUntil.delete(realm);
|
|
82
|
+
return fresh;
|
|
83
|
+
})
|
|
84
|
+
.finally(() => pendingFetches.delete(realm));
|
|
85
|
+
pendingFetches.set(realm, fetching);
|
|
86
|
+
return fetching;
|
|
87
|
+
}
|
|
88
|
+
async function signingKeyFor(realm, kid) {
|
|
89
|
+
const known = realmKeys.get(realm);
|
|
90
|
+
if (known) {
|
|
91
|
+
remember(realmKeys, realm, known);
|
|
92
|
+
}
|
|
93
|
+
const knownKey = known && keyById(known, kid);
|
|
94
|
+
const age = known ? Date.now() - known.fetchedAt : Infinity;
|
|
95
|
+
if (knownKey && age < keyCacheMs) {
|
|
96
|
+
return knownKey;
|
|
97
|
+
}
|
|
98
|
+
// Refetching for every unknown kid would let junk tokens spend the shared fetch budget.
|
|
99
|
+
if (known && !knownKey && age < refetchMinMs) {
|
|
100
|
+
throw new InvalidTokenError('Unknown signing key');
|
|
101
|
+
}
|
|
102
|
+
const blockedUntil = unavailableUntil.get(realm);
|
|
103
|
+
if (blockedUntil !== undefined && blockedUntil > Date.now()) {
|
|
104
|
+
if (knownKey) {
|
|
105
|
+
return knownKey;
|
|
106
|
+
}
|
|
107
|
+
throw new AuthUnavailableError(retryAfter(blockedUntil));
|
|
108
|
+
}
|
|
109
|
+
let latest;
|
|
110
|
+
try {
|
|
111
|
+
latest = await refreshKeys(realm);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
let unavailable = err;
|
|
115
|
+
if (!(err instanceof AuthUnavailableError)) {
|
|
116
|
+
const until = Date.now() + negativeCacheMs;
|
|
117
|
+
remember(unavailableUntil, realm, until);
|
|
118
|
+
console.error(`[adsp-sdk-mcp-server] Could not fetch sign-in keys for realm ${realm}.`);
|
|
119
|
+
unavailable = new AuthUnavailableError(retryAfter(until));
|
|
120
|
+
}
|
|
121
|
+
// Stale keys beat refusing every sign-in for the realm while Keycloak is unreachable.
|
|
122
|
+
if (knownKey) {
|
|
123
|
+
return knownKey;
|
|
124
|
+
}
|
|
125
|
+
throw unavailable;
|
|
126
|
+
}
|
|
127
|
+
const key = keyById(latest, kid);
|
|
128
|
+
if (!key) {
|
|
129
|
+
throw new InvalidTokenError('Unknown signing key');
|
|
130
|
+
}
|
|
131
|
+
return key;
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
async verify(realm, token) {
|
|
135
|
+
const decoded = (0, jsonwebtoken_1.decode)(token, { complete: true });
|
|
136
|
+
if (!decoded || typeof decoded.payload === 'string') {
|
|
137
|
+
throw new InvalidTokenError('Malformed token');
|
|
138
|
+
}
|
|
139
|
+
const issuer = issuerFor(realm);
|
|
140
|
+
// Checked before any key fetch, so a token for another realm or issuer costs no outbound request.
|
|
141
|
+
if (decoded.payload.iss !== issuer || decoded.header.alg !== 'RS256') {
|
|
142
|
+
throw new InvalidTokenError('Token is not for this realm');
|
|
143
|
+
}
|
|
144
|
+
const key = await signingKeyFor(realm, decoded.header.kid);
|
|
145
|
+
let payload;
|
|
146
|
+
try {
|
|
147
|
+
payload = (0, jsonwebtoken_1.verify)(token, key, {
|
|
148
|
+
algorithms: ['RS256'],
|
|
149
|
+
issuer,
|
|
150
|
+
audience: exports.MCP_AUDIENCE,
|
|
151
|
+
clockTolerance: CLOCK_TOLERANCE_SECONDS,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
throw new InvalidTokenError('Token verification failed');
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
token,
|
|
159
|
+
clientId: typeof payload['azp'] === 'string' ? payload['azp'] : '',
|
|
160
|
+
scopes: typeof payload['scope'] === 'string' ? payload['scope'].split(' ').filter(Boolean) : [],
|
|
161
|
+
expiresAt: payload.exp,
|
|
162
|
+
extra: { realm, sub: payload.sub },
|
|
163
|
+
};
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function metadataUrl(publicUrl, realm) {
|
|
168
|
+
return `${publicUrl}/.well-known/oauth-protected-resource/mcp/${realm}`;
|
|
169
|
+
}
|
|
170
|
+
/** Expects the realm in `req.params.tenantRealm`; sets `req.auth` for the MCP transport. */
|
|
171
|
+
function createAuthMiddleware({ verifier, publicUrl, }) {
|
|
172
|
+
return async (req, res, next) => {
|
|
173
|
+
const realm = req.params['tenantRealm'];
|
|
174
|
+
if (!exports.REALM_PATTERN.test(realm)) {
|
|
175
|
+
(0, guards_1.sendJsonRpcError)(res, 404, 'Unknown tenant realm');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const resourceMetadata = `resource_metadata="${metadataUrl(publicUrl, realm)}"`;
|
|
179
|
+
const token = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? '')?.[1] ?? '';
|
|
180
|
+
if (!token) {
|
|
181
|
+
res.setHeader('WWW-Authenticate', `Bearer ${resourceMetadata}`);
|
|
182
|
+
(0, guards_1.sendJsonRpcError)(res, 401, 'Sign-in required');
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
req.auth = await verifier.verify(realm, token);
|
|
187
|
+
next();
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
if (err instanceof AuthUnavailableError) {
|
|
191
|
+
(0, metrics_1.getMetrics)().recordRejection('auth_unavailable');
|
|
192
|
+
res.setHeader('Retry-After', String(err.retryAfterSeconds));
|
|
193
|
+
(0, guards_1.sendJsonRpcError)(res, 503, 'Sign-in is temporarily unavailable');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
(0, metrics_1.getMetrics)().recordRejection('auth');
|
|
197
|
+
res.setHeader('WWW-Authenticate', `Bearer error="invalid_token", ${resourceMetadata}`);
|
|
198
|
+
(0, guards_1.sendJsonRpcError)(res, 401, 'Sign-in rejected or expired');
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/** RFC 9728 protected-resource metadata, built only from configuration, never from request headers. */
|
|
203
|
+
function createProtectedResourceMetadataHandler({ publicUrl, accessServiceUrl, }) {
|
|
204
|
+
return (req, res) => {
|
|
205
|
+
const realm = req.params['tenantRealm'];
|
|
206
|
+
if (!exports.REALM_PATTERN.test(realm)) {
|
|
207
|
+
(0, guards_1.sendJsonRpcError)(res, 404, 'Unknown tenant realm');
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
res.json({
|
|
211
|
+
resource: `${publicUrl}/mcp/${realm}`,
|
|
212
|
+
authorization_servers: [`${accessServiceUrl}/auth/realms/${realm}`],
|
|
213
|
+
bearer_methods_supported: ['header'],
|
|
214
|
+
resource_name: 'ADSP SDK MCP server',
|
|
215
|
+
});
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
//# sourceMappingURL=auth.js.map
|
package/src/auth.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/auth.ts"],"names":[],"mappings":";;;AAwDA,kDAiJC;AAOD,oDAqCC;AAGD,wFAoBC;AA1QD,+CAA0D;AAC1D,uCAAsC;AACtC,qCAA4C;AAC5C,uCAAuC;AAE1B,QAAA,YAAY,GAAG,sCAAsC,CAAC;AAEnE,4FAA4F;AAC/E,QAAA,aAAa,GAAG,kCAAkC,CAAC;AAEhE,MAAM,eAAe,GAAG,MAAM,CAAC;AAC/B,MAAM,YAAY,GAAG,EAAE,GAAG,MAAM,CAAC;AACjC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,cAAc,GAAG,MAAM,CAAC;AAO9B,gFAAgF;AAChF,SAAS,OAAO,CAAC,EAAE,IAAI,EAAa,EAAE,GAAuB;IAC3D,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,I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AAC;IACL,CAAC,CAAC;AACJ,CAAC"}
|
package/src/config.d.ts
CHANGED
|
@@ -9,5 +9,15 @@ export interface McpServerConfig {
|
|
|
9
9
|
corsOrigins: '*' | string[];
|
|
10
10
|
shutdownDelayMs: number;
|
|
11
11
|
shutdownTimeoutMs: number;
|
|
12
|
+
/** Required in HTTP mode, where every request signs in; unused over stdio. */
|
|
13
|
+
auth?: HostedAuthConfig;
|
|
14
|
+
}
|
|
15
|
+
export interface HostedAuthConfig {
|
|
16
|
+
/** This server's external origin, used in sign-in metadata; never taken from request headers. */
|
|
17
|
+
publicUrl: string;
|
|
18
|
+
accessServiceUrl: string;
|
|
19
|
+
directoryServiceUrl: string;
|
|
12
20
|
}
|
|
13
21
|
export declare function readConfig(env?: NodeJS.ProcessEnv): McpServerConfig;
|
|
22
|
+
/** HTTP mode only: stdio users may set ADSP_ACCESS_SERVICE_URL or ADSP_DIRECTORY_SERVICE_URL as adsp-cli overrides. */
|
|
23
|
+
export declare function readHostedConfig(env?: NodeJS.ProcessEnv): McpServerConfig;
|
package/src/config.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.readConfig = readConfig;
|
|
4
|
+
exports.readHostedConfig = readHostedConfig;
|
|
4
5
|
function readInteger(env, name, defaultValue, minimum) {
|
|
5
6
|
const raw = env[name]?.trim();
|
|
6
7
|
if (!raw) {
|
|
@@ -34,6 +35,37 @@ function readCorsOrigins(env) {
|
|
|
34
35
|
}
|
|
35
36
|
return '*';
|
|
36
37
|
}
|
|
38
|
+
const AUTH_SETTINGS = {
|
|
39
|
+
publicUrl: 'MCP_PUBLIC_URL',
|
|
40
|
+
accessServiceUrl: 'ADSP_ACCESS_SERVICE_URL',
|
|
41
|
+
directoryServiceUrl: 'ADSP_DIRECTORY_SERVICE_URL',
|
|
42
|
+
};
|
|
43
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost']);
|
|
44
|
+
function readUrl(name, raw) {
|
|
45
|
+
let url;
|
|
46
|
+
try {
|
|
47
|
+
url = new URL(raw);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new Error(`${name} must be an absolute URL, but is "${raw}".`);
|
|
51
|
+
}
|
|
52
|
+
const allowed = url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname));
|
|
53
|
+
if (!allowed) {
|
|
54
|
+
throw new Error(`${name} must use https (plain http only on 127.0.0.1 or localhost), but is "${raw}".`);
|
|
55
|
+
}
|
|
56
|
+
return raw.replace(/\/+$/, '');
|
|
57
|
+
}
|
|
58
|
+
function readHostedAuth(env) {
|
|
59
|
+
const entries = Object.entries(AUTH_SETTINGS).map(([key, name]) => [key, name, env[name]?.trim()]);
|
|
60
|
+
const missing = entries.filter(([, , value]) => !value).map(([, name]) => name);
|
|
61
|
+
if (missing.length === entries.length) {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
if (missing.length > 0) {
|
|
65
|
+
throw new Error(`Hosted sign-in needs all of ${Object.values(AUTH_SETTINGS).join(', ')}; missing ${missing.join(', ')}.`);
|
|
66
|
+
}
|
|
67
|
+
return Object.fromEntries(entries.map(([key, name, value]) => [key, readUrl(name, value)]));
|
|
68
|
+
}
|
|
37
69
|
function readConfig(env = process.env) {
|
|
38
70
|
const shutdownDelayMs = readInteger(env, 'MCP_SHUTDOWN_DELAY_MS', 5000, 0);
|
|
39
71
|
const shutdownTimeoutMs = readInteger(env, 'MCP_SHUTDOWN_TIMEOUT_MS', 30000, 1);
|
|
@@ -51,4 +83,8 @@ function readConfig(env = process.env) {
|
|
|
51
83
|
shutdownTimeoutMs,
|
|
52
84
|
};
|
|
53
85
|
}
|
|
86
|
+
/** HTTP mode only: stdio users may set ADSP_ACCESS_SERVICE_URL or ADSP_DIRECTORY_SERVICE_URL as adsp-cli overrides. */
|
|
87
|
+
function readHostedConfig(env = process.env) {
|
|
88
|
+
return { ...readConfig(env), auth: readHostedAuth(env) };
|
|
89
|
+
}
|
|
54
90
|
//# sourceMappingURL=config.js.map
|
package/src/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/config.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/config.ts"],"names":[],"mappings":";;AA4FA,gCAmBC;AAGD,4CAEC;AA9FD,SAAS,WAAW,CAAC,GAAsB,EAAE,IAAY,EAAE,YAAoB,EAAE,OAAe;IAC9F,MAAM,GAAG,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;IAC9B,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,YAAY,CAAC;IACtB,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,OAAO,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,mCAAmC,OAAO,aAAa,GAAG,IAAI,CAAC,CAAC;IACzF,CAAC;IACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;AACrB,CAAC;AAED,SAAS,gBAAgB,CAAC,GAAsB;IAC9C,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC;IACzC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,aAAa,CAAC;IACvB,CAAC;IACD,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,OAAO,EAAE,CAAC;QACtC,OAAO,GAAG,KAAK,MAAM,CAAC;IACxB,CAAC;IACD,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AA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GAAG,WAAW,CAAC,GAAG,EAAE,uBAAuB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC3E,MAAM,iBAAiB,GAAG,WAAW,CAAC,GAAG,EAAE,yBAAyB,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IAChF,IAAI,eAAe,IAAI,iBAAiB,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CACb,0BAA0B,eAAe,mDAAmD,iBAAiB,IAAI,CAClH,CAAC;IACJ,CAAC;IAED,OAAO;QACL,WAAW,EAAE,WAAW,CAAC,GAAG,EAAE,mBAAmB,EAAE,EAAE,EAAE,CAAC,CAAC;QACzD,cAAc,EAAE,WAAW,CAAC,GAAG,EAAE,uBAAuB,EAAE,IAAI,EAAE,CAAC,CAAC;QAClE,kBAAkB,EAAE,WAAW,CAAC,GAAG,EAAE,2BAA2B,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1E,qBAAqB,EAAE,WAAW,CAAC,GAAG,EAAE,8BAA8B,EAAE,CAAC,EAAE,CAAC,CAAC;QAC7E,YAAY,EAAE,gBAAgB,CAAC,GAAG,CAAC;QACnC,WAAW,EAAE,eAAe,CAAC,GAAG,CAAC;QACjC,eAAe;QACf,iBAAiB;KAClB,CAAC;AACJ,CAAC;AAED,uHAAuH;AACvH,SAAgB,gBAAgB,CAAC,MAAyB,OAAO,CAAC,GAAG;IACnE,OAAO,EAAE,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC;AAC3D,CAAC"}
|
package/src/guards.js
CHANGED
|
@@ -25,8 +25,8 @@ function createCorsAndOriginGuard(corsOrigins) {
|
|
|
25
25
|
return (req, res, next) => {
|
|
26
26
|
res.vary('Origin');
|
|
27
27
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
|
|
28
|
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, mcp-session-id, mcp-protocol-version');
|
|
29
|
-
res.setHeader('Access-Control-Expose-Headers', 'mcp-session-id');
|
|
28
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, mcp-session-id, mcp-protocol-version');
|
|
29
|
+
res.setHeader('Access-Control-Expose-Headers', 'mcp-session-id, WWW-Authenticate');
|
|
30
30
|
const origin = req.headers.origin;
|
|
31
31
|
if (origin !== undefined) {
|
|
32
32
|
if (!isAllowedOrigin(origin, corsOrigins)) {
|
package/src/guards.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guards.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/guards.ts"],"names":[],"mappings":";;AAQA,4CAEC;AAaD,4DAuBC;AAGD,oCAEC;AAED,0CAgBC;AAGD,gDA2BC;AAlGD,2DAA+C;AAE/C,uCAAuC;AAGvC,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAEpC,SAAgB,gBAAgB,CAAC,GAAqB,EAAE,MAAc,EAAE,OAAe;IACrF,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;AAC1F,CAAC;AAED,SAAS,eAAe,CAAC,MAAc,EAAE,WAA2C;IAClF,qFAAqF;IACrF,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;QACtB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,6GAA6G;IAC7G,wGAAwG;IACxG,OAAO,WAAW,KAAK,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC7D,CAAC;AAED,yHAAyH;AACzH,SAAgB,wBAAwB,CAAC,WAA2C;IAClF,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC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ateAdspMcpServerOptions {
|
|
|
6
6
|
port?: number;
|
|
7
7
|
host?: string;
|
|
8
8
|
env?: NodeJS.ProcessEnv;
|
|
9
|
-
/** Defaults to `
|
|
9
|
+
/** Defaults to `readHostedConfig(env)`. */
|
|
10
10
|
config?: McpServerConfig;
|
|
11
11
|
/** Where SIGTERM and SIGINT arrive; defaults to `process`. */
|
|
12
12
|
signals?: NodeJS.EventEmitter;
|
package/src/hosted.js
CHANGED
|
@@ -6,7 +6,7 @@ const http_1 = require("./http");
|
|
|
6
6
|
const lifecycle_1 = require("./lifecycle");
|
|
7
7
|
const metrics_1 = require("./metrics");
|
|
8
8
|
/** Runs the hosted HTTP server: metrics, the app, request deadlines, readiness and the graceful drain on signals. */
|
|
9
|
-
async function startMcpHttpServer({ port, host, env = process.env, config = (0, config_1.
|
|
9
|
+
async function startMcpHttpServer({ port, host, env = process.env, config = (0, config_1.readHostedConfig)(env), signals = process, exit = (code) => process.exit(code), ...serverOptions } = {}) {
|
|
10
10
|
// Started before the app so the docs index build, which the app triggers, is recorded.
|
|
11
11
|
const metrics = await (0, metrics_1.startMetricsFromEnv)(env);
|
|
12
12
|
const lifecycle = (0, lifecycle_1.createLifecycle)();
|
package/src/hosted.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hosted.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/hosted.ts"],"names":[],"mappings":";;AA0BA,gDAiCC;AAzDD,
|
|
1
|
+
{"version":3,"file":"hosted.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/hosted.ts"],"names":[],"mappings":";;AA0BA,gDAiCC;AAzDD,qCAA6D;AAC7D,iCAA+D;AAC/D,2CAAsE;AACtE,uCAAgD;AAoBhD,qHAAqH;AAC9G,KAAK,UAAU,kBAAkB,CAAC,EACvC,IAAI,EACJ,IAAI,EACJ,GAAG,GAAG,OAAO,CAAC,GAAG,EACjB,MAAM,GAAG,IAAA,yBAAgB,EA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,EAAE,CAAC;AAC7C,CAAC"}
|
package/src/http.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { McpServerConfig } from './config';
|
|
|
4
4
|
import { ServerLifecycle } from './lifecycle';
|
|
5
5
|
import { CreateAdspMcpServerOptions } from './server';
|
|
6
6
|
export interface McpHttpAppOptions extends CreateAdspMcpServerOptions {
|
|
7
|
-
/** Defaults to `
|
|
7
|
+
/** Defaults to `readHostedConfig()` over `process.env`. */
|
|
8
8
|
config?: McpServerConfig;
|
|
9
9
|
/** Drives `/ready`; shutdown flips it. */
|
|
10
10
|
lifecycle?: ServerLifecycle;
|
package/src/http.js
CHANGED
|
@@ -6,6 +6,7 @@ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamable
|
|
|
6
6
|
const express = require("express");
|
|
7
7
|
const http_1 = require("http");
|
|
8
8
|
const perf_hooks_1 = require("perf_hooks");
|
|
9
|
+
const auth_1 = require("./auth");
|
|
9
10
|
const config_1 = require("./config");
|
|
10
11
|
const guards_1 = require("./guards");
|
|
11
12
|
const lifecycle_1 = require("./lifecycle");
|
|
@@ -64,7 +65,7 @@ function methodNotAllowed(_req, res) {
|
|
|
64
65
|
.set('Allow', 'POST')
|
|
65
66
|
.json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed.' }, id: null });
|
|
66
67
|
}
|
|
67
|
-
function createMcpHttpApp({ config = (0, config_1.
|
|
68
|
+
function createMcpHttpApp({ config = (0, config_1.readHostedConfig)(), lifecycle = (0, lifecycle_1.createLifecycle)(), ...serverOptions } = {}) {
|
|
68
69
|
(0, server_1.loadAdspMcpTools)(serverOptions);
|
|
69
70
|
(0, liveToolLimit_1.configureLiveToolLimit)({ maxConcurrent: config.liveToolMaxConcurrent, waitMs: config.inFlightWaitMs });
|
|
70
71
|
// No express.json(): the transport reads the body so parse and size errors come back as JSON-RPC.
|
|
@@ -93,10 +94,31 @@ function createMcpHttpApp({ config = (0, config_1.readConfig)(), lifecycle = (0,
|
|
|
93
94
|
}
|
|
94
95
|
res.json({ status: 'ready' });
|
|
95
96
|
});
|
|
96
|
-
|
|
97
|
-
|
|
97
|
+
const corsAndOrigin = (0, guards_1.createCorsAndOriginGuard)(config.corsOrigins);
|
|
98
|
+
// Shared by both endpoints, so a client can't double its budget by spreading requests across them.
|
|
99
|
+
const rateLimit = (0, guards_1.createRateLimit)(config.rateLimitPerMinute);
|
|
100
|
+
// One cap per endpoint, so requests without a token can never take the slots signed-in callers need.
|
|
101
|
+
const createEndpointInFlightGate = () => (0, guards_1.createInFlightGate)(new semaphore_1.Semaphore(config.maxInFlight, { maxWaiters: config.maxInFlight }), config.inFlightWaitMs);
|
|
102
|
+
app.use('/mcp', corsAndOrigin);
|
|
103
|
+
// Never asks for a token, so clients that can't sign in still get the bundled content; live tools aren't listed.
|
|
104
|
+
app.post('/mcp', rateLimit, createEndpointInFlightGate(), createStatelessPostHandler({ ...serverOptions, offlineToolsOnly: true }));
|
|
98
105
|
app.get('/mcp', methodNotAllowed);
|
|
99
106
|
app.delete('/mcp', methodNotAllowed);
|
|
107
|
+
if (!config.auth) {
|
|
108
|
+
console.error('[adsp-sdk-mcp-server] MCP_PUBLIC_URL, ADSP_ACCESS_SERVICE_URL and ADSP_DIRECTORY_SERVICE_URL are not set, so only /mcp is served.');
|
|
109
|
+
return app;
|
|
110
|
+
}
|
|
111
|
+
const { publicUrl, accessServiceUrl, directoryServiceUrl } = config.auth;
|
|
112
|
+
const verifier = (0, auth_1.createTokenVerifier)({ accessServiceUrl });
|
|
113
|
+
const metadataPath = '/.well-known/oauth-protected-resource/mcp/:tenantRealm';
|
|
114
|
+
app.use(metadataPath, corsAndOrigin);
|
|
115
|
+
app.get(metadataPath, (0, auth_1.createProtectedResourceMetadataHandler)({ publicUrl, accessServiceUrl }));
|
|
116
|
+
// Each tenant realm is its own issuer, so the signed-in endpoint names the realm.
|
|
117
|
+
app.post('/mcp/:tenantRealm', rateLimit,
|
|
118
|
+
// Before the gate, so requests without a valid token never hold an in-flight slot.
|
|
119
|
+
(0, auth_1.createAuthMiddleware)({ verifier, publicUrl }), createEndpointInFlightGate(), createStatelessPostHandler({ ...serverOptions, hostedAuth: { directoryServiceUrl } }));
|
|
120
|
+
app.get('/mcp/:tenantRealm', methodNotAllowed);
|
|
121
|
+
app.delete('/mcp/:tenantRealm', methodNotAllowed);
|
|
100
122
|
return app;
|
|
101
123
|
}
|
|
102
124
|
/**
|
package/src/http.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/http.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/http.ts"],"names":[],"mappings":";;AA4EA,4CAkFC;AAYD,kDASC;AAnLD,0FAAmG;AACnG,mCAAmC;AACnC,+BAA0D;AAC1D,2CAAyC;AACzC,iCAA2G;AAC3G,qCAA6D;AAC7D,qCAAyF;AACzF,2CAA+D;AAC/D,uCAAwD;AACxD,2CAAwC;AACxC,qCAA6F;AAC7F,yDAA+D;AAE/D,MAAM,sBAAsB,GAAG,IAAI,GAAG,IAAI,CAAC;AAS3C,SAAS,0BAA0B,CAAC,OAAmC;IACrE,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QACxB,MAAM,OAAO,GAAG,wBAAW,CAAC,GAAG,EAAE,CAAC;QAClC,MAAM,OAAO,GAAG,IAAA,oBAAU,GAAE,CAAC;QAC7B,IAAI,MAAM,GAAG,UAAU,CAAC;QACxB,IAAI,YAAY,GAAG,CAAC,CAAC;QAErB,MAAM,MAAM,GAAG,IAAA,4BAAmB,EAAC,OAAO,CAAC,CAAC;QAC5C,MAAM,SAAS,GAAG,IAAI,iDAA6B,CAAC;YAClD,kBAAkB,EAAE,SAAS;YAC7B,kBAAkB,EAAE,IAAI;YACxB,kBAAkB,EAAE,sBAAsB;SAC3C,CAAC,CAAC;QACH,kGAAk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IAC1F,OAAO,IAAA,mBAAY,EACjB;QACE,cAAc,EAAE,OAAO,CAAC,gBAAgB,IAAI,MAAM;QAClD,cAAc,EAAE,OAAO,CAAC,gBAAgB,IAAI,MAAM;QAClD,2BAA2B,EAAE,OAAO,CAAC,6BAA6B,IAAI,KAAK;KAC5E,EACD,GAAG,CACJ,CAAC;AACJ,CAAC"}
|
package/src/instructions.d.ts
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Returned in the initialize result. Covers only what no single tool description can: which tool answers which
|
|
3
|
-
* kind of question, which tools need a login, and how fresh the bundled content is. Keep it short and never restate
|
|
4
|
-
* a tool description (server.spec.ts checks this); clients may truncate or ignore instructions.
|
|
5
|
-
*/
|
|
6
1
|
export declare const SERVER_INSTRUCTIONS: string;
|
|
2
|
+
/** For the hosted /mcp endpoint, which serves only the offline tools and never asks for a sign-in. */
|
|
3
|
+
export declare const OFFLINE_ENDPOINT_INSTRUCTIONS: string;
|
package/src/instructions.js
CHANGED
|
@@ -1,22 +1,35 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SERVER_INSTRUCTIONS = void 0;
|
|
3
|
+
exports.OFFLINE_ENDPOINT_INSTRUCTIONS = exports.SERVER_INSTRUCTIONS = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* Returned in the initialize result. Covers only what no single tool description can: which tool answers which
|
|
6
6
|
* kind of question, which tools need a login, and how fresh the bundled content is. Keep it short and never restate
|
|
7
7
|
* a tool description (server.spec.ts checks this); clients may truncate or ignore instructions.
|
|
8
8
|
*/
|
|
9
|
-
|
|
9
|
+
const TOOL_CHOICE = [
|
|
10
10
|
'Use this server to build services and apps on ADSP (Alberta Digital Service Platform). Pick the tool by the question:',
|
|
11
11
|
'- Before designing or building any capability of an ADSP app, call find_adsp_services with the need. If a result',
|
|
12
12
|
' has ask set, put its fitQuestions to the user rather than picking a service yourself. noMatch: no service fits.',
|
|
13
13
|
'- Platform concepts or how-tos: search_adsp_docs, then read_adsp_doc. Browse services/ with list_adsp_docs.',
|
|
14
14
|
'- Writing a Node service: get_platform_quickstart first, then search_sdk_reference for a specific symbol.',
|
|
15
15
|
"- Calling a service's REST API: search_service_endpoints, then read_service_endpoint.",
|
|
16
|
+
];
|
|
17
|
+
const CONTENT_FRESHNESS = [
|
|
18
|
+
'Bundled content can lag the platform. get_adsp_mcp_server_info says when and from which commit it was built;',
|
|
19
|
+
'mention that when a detail may be out of date.',
|
|
20
|
+
];
|
|
21
|
+
exports.SERVER_INSTRUCTIONS = [
|
|
22
|
+
...TOOL_CHOICE,
|
|
16
23
|
'- Roles a service account needs, or the configuration a platform service accepts from yours: list_service_roles,',
|
|
17
24
|
' get_service_configuration_schema. Only these two reach the live platform; the user must run',
|
|
18
25
|
' `npx @abgov/adsp-cli login` first. Every other tool answers offline from content bundled at build time.',
|
|
19
|
-
|
|
20
|
-
|
|
26
|
+
...CONTENT_FRESHNESS,
|
|
27
|
+
].join('\n');
|
|
28
|
+
/** For the hosted /mcp endpoint, which serves only the offline tools and never asks for a sign-in. */
|
|
29
|
+
exports.OFFLINE_ENDPOINT_INSTRUCTIONS = [
|
|
30
|
+
...TOOL_CHOICE,
|
|
31
|
+
'- Roles a service account needs, or the configuration a platform service accepts from yours, are read live and',
|
|
32
|
+
' need a sign-in: connect to /mcp/<tenant realm> on this server instead. Every tool here answers offline.',
|
|
33
|
+
...CONTENT_FRESHNESS,
|
|
21
34
|
].join('\n');
|
|
22
35
|
//# sourceMappingURL=instructions.js.map
|
package/src/instructions.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instructions.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/instructions.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"instructions.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/instructions.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,MAAM,WAAW,GAAG;IAClB,uHAAuH;IACvH,kHAAkH;IAClH,mHAAmH;IACnH,6GAA6G;IAC7G,2GAA2G;IAC3G,uFAAuF;CACxF,CAAC;AAEF,MAAM,iBAAiB,GAAG;IACxB,8GAA8G;IAC9G,gDAAgD;CACjD,CAAC;AAEW,QAAA,mBAAmB,GAAG;IACjC,GAAG,WAAW;IACd,kHAAkH;IAClH,+FAA+F;IAC/F,2GAA2G;IAC3G,GAAG,iBAAiB;CACrB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb,sGAAsG;AACzF,QAAA,6BAA6B,GAAG;IAC3C,GAAG,WAAW;IACd,gHAAgH;IAChH,2GAA2G;IAC3G,GAAG,iBAAiB;CACrB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC"}
|
package/src/main.js
CHANGED
|
@@ -15,7 +15,7 @@ function resolveTransport() {
|
|
|
15
15
|
}
|
|
16
16
|
async function main() {
|
|
17
17
|
const transport = resolveTransport();
|
|
18
|
-
const config = (0, config_1.readConfig)();
|
|
18
|
+
const config = transport === 'http' ? (0, config_1.readHostedConfig)() : (0, config_1.readConfig)();
|
|
19
19
|
console.error(`[adsp-sdk-mcp-server] transport=${transport}`);
|
|
20
20
|
if (transport === 'http') {
|
|
21
21
|
await (0, hosted_1.startMcpHttpServer)({ config });
|
package/src/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/main.ts"],"names":[],"mappings":";;;AACA,wEAAiF;AACjF,
|
|
1
|
+
{"version":3,"file":"main.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/main.ts"],"names":[],"mappings":";;;AACA,wEAAiF;AACjF,qCAAwD;AACxD,qCAA8C;AAC9C,qCAA+C;AAC/C,yDAA+D;AAI/D,SAAS,gBAAgB;IACvB,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,OAAO,CAAC;IACpD,IAAI,GAAG,KAAK,OAAO,IAAI,GAAG,KAAK,MAAM;QAAE,OAAO,GAAG,CAAC;IAClD,OAAO,CAAC,KAAK,CAAC,gDAAgD,GAAG,oDAAoD,CAAC,CAAC;IACvH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,KAAK,UAAU,IAAI;IACjB,MAAM,SAAS,GAAG,gBAAgB,EAAE,CAAC;IACrC,MAAM,MAAM,GAAG,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,IAAA,yBAAgB,GAAE,CAAC,CAAC,CAAC,IAAA,mBAAU,GAAE,CAAC;IACxE,OAAO,CAAC,KAAK,CAAC,mCAAmC,SAAS,EAAE,CAAC,CAAC;IAE9D,IAAI,SAAS,KAAK,MAAM,EAAE,CAAC;QACzB,MAAM,IAAA,2BAAkB,EAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACvC,CAAC;SAAM,CAAC;QACN,IAAA,sCAAsB,EAAC,EAAE,aAAa,EAAE,MAAM,CAAC,qBAAqB,EAAE,MAAM,EAAE,MAAM,CAAC,cAAc,EAAE,CAAC,CAAC;QACvG,MAAM,MAAM,GAAG,IAAA,4BAAmB,GAAE,CAAC;QACrC,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,+BAAoB,EAAE,CAAC,CAAC;IACnD,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,GAAG,CAAC,CAAC;IAC3D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
|
package/src/metrics.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { MeterProvider } from '@opentelemetry/api';
|
|
2
|
-
export type RejectionReason = 'in_flight_cap' | 'rate_limit' | 'origin' | 'live_tool_cap';
|
|
2
|
+
export type RejectionReason = 'in_flight_cap' | 'rate_limit' | 'origin' | 'live_tool_cap' | 'auth' | 'auth_unavailable';
|
|
3
3
|
export type ToolErrorType = 'tool_error' | 'exception' | 'unknown_tool' | 'busy';
|
|
4
4
|
export type UpstreamErrorType = 'http_4xx' | 'http_5xx' | 'network' | 'not_in_directory' | 'not_authenticated' | 'other';
|
|
5
5
|
export interface McpMetrics {
|
package/src/server.d.ts
CHANGED
|
@@ -5,12 +5,20 @@ export interface CreateAdspMcpServerOptions {
|
|
|
5
5
|
docsRoot?: string;
|
|
6
6
|
/** Root directory of bundled OpenAPI specs. Defaults to the assets copied alongside the built package. */
|
|
7
7
|
apiSpecsRoot?: string;
|
|
8
|
+
/** Hosted mode: live tools use each request's verified token and this directory, never the CLI login. */
|
|
9
|
+
hostedAuth?: {
|
|
10
|
+
directoryServiceUrl: string;
|
|
11
|
+
};
|
|
8
12
|
/** The capability catalog find_adsp_services ranks. Defaults to the one bundled with the package. */
|
|
9
13
|
capabilitiesPath?: string;
|
|
14
|
+
/** Serve only the tools that answer from bundled content, for callers that haven't signed in. */
|
|
15
|
+
offlineToolsOnly?: boolean;
|
|
10
16
|
}
|
|
11
17
|
export interface AdspMcpTools {
|
|
12
18
|
tools: (ToolDefinition | LiveToolDefinition)[];
|
|
13
19
|
toolsByName: Map<string, ToolDefinition | LiveToolDefinition>;
|
|
20
|
+
offlineTools: ToolDefinition[];
|
|
21
|
+
offlineToolsByName: Map<string, ToolDefinition>;
|
|
14
22
|
}
|
|
15
23
|
export declare function loadAdspMcpTools(options?: CreateAdspMcpServerOptions): AdspMcpTools;
|
|
16
24
|
export declare function createAdspMcpServer(options?: CreateAdspMcpServerOptions): Server;
|
package/src/server.js
CHANGED
|
@@ -20,6 +20,7 @@ const registerQuickstartTool_1 = require("./tools/registerQuickstartTool");
|
|
|
20
20
|
const registerServiceRolesTool_1 = require("./tools/registerServiceRolesTool");
|
|
21
21
|
const registerSdkTools_1 = require("./tools/registerSdkTools");
|
|
22
22
|
const registerServerInfoTool_1 = require("./tools/registerServerInfoTool");
|
|
23
|
+
const types_1 = require("./tools/types");
|
|
23
24
|
const version_1 = require("./version");
|
|
24
25
|
// Compiled output places this file under dist/.../src/, while the docs asset copy lands one level up at dist/.../assets/docs.
|
|
25
26
|
const DEFAULT_DOCS_ROOT = (0, path_1.join)(__dirname, '..', 'assets', 'docs');
|
|
@@ -52,13 +53,22 @@ function loadAdspMcpTools(options = {}) {
|
|
|
52
53
|
...(0, registerServerInfoTool_1.createServerInfoTool)(docs),
|
|
53
54
|
...(0, registerApiTools_1.createApiTools)(lazy(() => new apiSpecsRepository_1.ApiSpecsRepository(apiSpecsRoot))),
|
|
54
55
|
];
|
|
55
|
-
const
|
|
56
|
+
const offlineTools = tools.filter(types_1.isOfflineTool);
|
|
57
|
+
const loaded = {
|
|
58
|
+
tools,
|
|
59
|
+
toolsByName: new Map(tools.map((tool) => [tool.name, tool])),
|
|
60
|
+
offlineTools,
|
|
61
|
+
offlineToolsByName: new Map(offlineTools.map((tool) => [tool.name, tool])),
|
|
62
|
+
};
|
|
56
63
|
toolsByRoots.set(cacheKey, loaded);
|
|
57
64
|
(0, metrics_1.getMetrics)().recordDocsIndexBuild(secondsSince(started));
|
|
58
65
|
return loaded;
|
|
59
66
|
}
|
|
60
67
|
function createAdspMcpServer(options = {}) {
|
|
61
|
-
const
|
|
68
|
+
const loaded = loadAdspMcpTools(options);
|
|
69
|
+
const { tools, toolsByName } = options.offlineToolsOnly
|
|
70
|
+
? { tools: loaded.offlineTools, toolsByName: loaded.offlineToolsByName }
|
|
71
|
+
: loaded;
|
|
62
72
|
// Deliberately using the low-level Server (McpServer is recommended for typical cases) rather than an oversight:
|
|
63
73
|
// this workspace hoists multiple physical copies of zod (root zod@3.x plus nested zod@4.x/3.x under unrelated
|
|
64
74
|
// deps like @mastra/schema-compat). McpServer.registerTool's zod-compat generics reconcile our zod against the
|
|
@@ -67,7 +77,10 @@ function createAdspMcpServer(options = {}) {
|
|
|
67
77
|
// would fix it but risks changing runtime behavior for unrelated consumers (e.g. agent-service's Mastra agent
|
|
68
78
|
// config). Server + setRequestHandler avoids the SDK's zod-compat generics entirely; tools validate their own
|
|
69
79
|
// args with zod as a plain value (see tools/*.ts), never passing a schema through the SDK's type machinery.
|
|
70
|
-
const server = new index_js_1.Server({ name: 'adsp-sdk-mcp-server', version: (0, version_1.readPackageVersion)() }, {
|
|
80
|
+
const server = new index_js_1.Server({ name: 'adsp-sdk-mcp-server', version: (0, version_1.readPackageVersion)() }, {
|
|
81
|
+
capabilities: { tools: {} },
|
|
82
|
+
instructions: options.offlineToolsOnly ? instructions_1.OFFLINE_ENDPOINT_INSTRUCTIONS : instructions_1.SERVER_INSTRUCTIONS,
|
|
83
|
+
});
|
|
71
84
|
server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
|
|
72
85
|
tools: tools.map((tool) => ({
|
|
73
86
|
name: tool.name,
|
|
@@ -80,14 +93,28 @@ function createAdspMcpServer(options = {}) {
|
|
|
80
93
|
server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
|
|
81
94
|
const started = perf_hooks_1.performance.now();
|
|
82
95
|
const tool = toolsByName.get(request.params.name);
|
|
96
|
+
if (!tool && loaded.toolsByName.has(request.params.name)) {
|
|
97
|
+
(0, metrics_1.getMetrics)().recordToolCall(request.params.name, secondsSince(started), 'tool_error');
|
|
98
|
+
return { isError: true, content: [{ type: 'text', text: liveToolNeedsSignIn(request.params.name) }] };
|
|
99
|
+
}
|
|
83
100
|
if (!tool) {
|
|
84
101
|
// The label is fixed so client-supplied names can't create new metric series.
|
|
85
102
|
(0, metrics_1.getMetrics)().recordToolCall('unknown', secondsSince(started), 'unknown_tool');
|
|
86
103
|
return { isError: true, content: [{ type: 'text', text: `Unknown tool: ${request.params.name}` }] };
|
|
87
104
|
}
|
|
105
|
+
let caller;
|
|
106
|
+
if (options.hostedAuth) {
|
|
107
|
+
const accessToken = extra.authInfo?.token;
|
|
108
|
+
// Refused rather than falling through, so a hosted server never acts with its own CLI login.
|
|
109
|
+
if (!accessToken) {
|
|
110
|
+
(0, metrics_1.getMetrics)().recordToolCall(tool.name, secondsSince(started), 'tool_error');
|
|
111
|
+
return { isError: true, content: [{ type: 'text', text: 'Sign-in required. Sign in from your MCP client.' }] };
|
|
112
|
+
}
|
|
113
|
+
caller = { accessToken, directoryServiceUrl: options.hostedAuth.directoryServiceUrl };
|
|
114
|
+
}
|
|
88
115
|
try {
|
|
89
116
|
// clean-code-ignore: 2.18 — ToolDefinition.handler is documented (tools/types.ts) as a pure, side-effect-free lookup.
|
|
90
|
-
const result = await tool.handler(request.params.arguments ?? {}, { signal: extra.signal });
|
|
117
|
+
const result = await tool.handler(request.params.arguments ?? {}, { signal: extra.signal, caller });
|
|
91
118
|
(0, metrics_1.getMetrics)().recordToolCall(tool.name, secondsSince(started), toolErrorType(result));
|
|
92
119
|
return result;
|
|
93
120
|
}
|
|
@@ -98,6 +125,10 @@ function createAdspMcpServer(options = {}) {
|
|
|
98
125
|
});
|
|
99
126
|
return server;
|
|
100
127
|
}
|
|
128
|
+
function liveToolNeedsSignIn(name) {
|
|
129
|
+
return (`${name} reads the live platform, so it needs a sign-in. Connect to /mcp/<tenant realm> on this server and ` +
|
|
130
|
+
'sign in, or run the server locally with npx @abgov/adsp-sdk-mcp-server.');
|
|
131
|
+
}
|
|
101
132
|
function toolErrorType(result) {
|
|
102
133
|
if ((0, liveToolLimit_1.isBusyResult)(result)) {
|
|
103
134
|
return 'busy';
|
package/src/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/server.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/server.ts"],"names":[],"mappings":";;AAsDA,4CAgCC;AAED,kDAoEC;AA5JD,wEAAmE;AACnE,iEAAmH;AACnH,+BAAqC;AACr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IACnC,OAAO,CAAC,wBAAW,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,GAAG,IAAI,CAAC;AAC9C,CAAC"}
|
|
@@ -6,15 +6,22 @@ const metrics_1 = require("../metrics");
|
|
|
6
6
|
const types_1 = require("./types");
|
|
7
7
|
const liveToolLimit_1 = require("./liveToolLimit");
|
|
8
8
|
const upstreamErrors_1 = require("./upstreamErrors");
|
|
9
|
-
function describeError(err) {
|
|
9
|
+
function describeError(err, signedInCaller) {
|
|
10
10
|
if (err instanceof adsp_cli_1.ServiceNotInDirectoryError) {
|
|
11
11
|
return err.message;
|
|
12
12
|
}
|
|
13
13
|
if (err instanceof adsp_cli_1.HttpRequestError) {
|
|
14
14
|
if (err.status === 401) {
|
|
15
|
+
if (signedInCaller) {
|
|
16
|
+
return upstreamErrors_1.CALLER_SIGN_IN_REJECTED;
|
|
17
|
+
}
|
|
15
18
|
return 'Access token was rejected (401). Run `npx @abgov/adsp-cli login` again to refresh it.';
|
|
16
19
|
}
|
|
17
20
|
if (err.status === 403) {
|
|
21
|
+
if (signedInCaller) {
|
|
22
|
+
return ('Access denied (403) reading configuration-service schemas. This is more likely the wrong tenant realm ' +
|
|
23
|
+
'than a missing role — check the realm in your MCP server URL.');
|
|
24
|
+
}
|
|
18
25
|
return ('Access denied (403) reading configuration-service schemas. This is more likely the wrong tenant realm ' +
|
|
19
26
|
'or environment than a missing role — check ADSP_TENANT_REALM and ADSP_ENV.');
|
|
20
27
|
}
|
|
@@ -31,6 +38,7 @@ function describeError(err) {
|
|
|
31
38
|
function createConfigurationSchemaTools() {
|
|
32
39
|
return [
|
|
33
40
|
{
|
|
41
|
+
kind: 'live',
|
|
34
42
|
name: 'get_service_configuration_schema',
|
|
35
43
|
annotations: types_1.LIVE_TOOL_ANNOTATIONS,
|
|
36
44
|
description: 'Returns the configuration schema(s) for ADSP platform services, read live from configuration-service. ' +
|
|
@@ -49,7 +57,8 @@ function createConfigurationSchemaTools() {
|
|
|
49
57
|
},
|
|
50
58
|
},
|
|
51
59
|
handler: (args, context) => (0, liveToolLimit_1.withLiveToolPermit)(async () => {
|
|
52
|
-
const
|
|
60
|
+
const caller = context?.caller;
|
|
61
|
+
const tokenResult = caller ? { status: 'ok', token: caller.accessToken } : await (0, adsp_cli_1.getAccessToken)();
|
|
53
62
|
if (tokenResult.status === 'not-authenticated') {
|
|
54
63
|
(0, metrics_1.getMetrics)().recordUpstreamError('get_service_configuration_schema', 'not_authenticated');
|
|
55
64
|
return {
|
|
@@ -60,7 +69,7 @@ function createConfigurationSchemaTools() {
|
|
|
60
69
|
};
|
|
61
70
|
}
|
|
62
71
|
try {
|
|
63
|
-
const directoryServiceUrl = (0, adsp_cli_1.getDirectoryServiceUrl)();
|
|
72
|
+
const directoryServiceUrl = caller ? caller.directoryServiceUrl : (0, adsp_cli_1.getDirectoryServiceUrl)();
|
|
64
73
|
const schemas = await (0, adsp_cli_1.getServiceConfigurationSchemas)(tokenResult.token, directoryServiceUrl, args.serviceId);
|
|
65
74
|
return {
|
|
66
75
|
content: [{ type: 'text', text: JSON.stringify(schemas, null, 2) }],
|
|
@@ -68,7 +77,7 @@ function createConfigurationSchemaTools() {
|
|
|
68
77
|
}
|
|
69
78
|
catch (err) {
|
|
70
79
|
(0, metrics_1.getMetrics)().recordUpstreamError('get_service_configuration_schema', (0, upstreamErrors_1.classifyUpstreamError)(err));
|
|
71
|
-
return { isError: true, content: [{ type: 'text', text: describeError(err) }] };
|
|
80
|
+
return { isError: true, content: [{ type: 'text', text: describeError(err, caller !== undefined) }] };
|
|
72
81
|
}
|
|
73
82
|
}, context?.signal),
|
|
74
83
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerConfigurationSchemaTool.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk-mcp-server/src/tools/registerConfigurationSchemaTool.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"registerConfigurationSchemaTool.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk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,EAAE,CAAC,CAAC,EAAE,CAAC;qBACpE,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAA,oBAAU,GAAE,CAAC,mBAAmB,CAAC,kCAAkC,EAAE,IAAA,sCAAqB,EAAC,GAAG,CAAC,CAAC,CAAC;oBACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,GAAG,EAAE,MAAM,KAAK,SAAS,CAAC,EAAE,CAAC,EAAE,CAAC;gBACxG,CAAC;YACH,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC;SACtB;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -6,15 +6,22 @@ const metrics_1 = require("../metrics");
|
|
|
6
6
|
const types_1 = require("./types");
|
|
7
7
|
const liveToolLimit_1 = require("./liveToolLimit");
|
|
8
8
|
const upstreamErrors_1 = require("./upstreamErrors");
|
|
9
|
-
function describeError(err) {
|
|
9
|
+
function describeError(err, signedInCaller) {
|
|
10
10
|
if (err instanceof adsp_cli_1.ServiceNotInDirectoryError) {
|
|
11
11
|
return err.message;
|
|
12
12
|
}
|
|
13
13
|
if (err instanceof adsp_cli_1.HttpRequestError) {
|
|
14
14
|
if (err.status === 401) {
|
|
15
|
+
if (signedInCaller) {
|
|
16
|
+
return upstreamErrors_1.CALLER_SIGN_IN_REJECTED;
|
|
17
|
+
}
|
|
15
18
|
return 'Access token was rejected (401). Run `npx @abgov/adsp-cli login` again to refresh it.';
|
|
16
19
|
}
|
|
17
20
|
if (err.status === 403) {
|
|
21
|
+
if (signedInCaller) {
|
|
22
|
+
return ('Access denied (403) reading tenant-service configuration. This is more likely the wrong tenant realm ' +
|
|
23
|
+
'than a missing role — check the realm in your MCP server URL.');
|
|
24
|
+
}
|
|
18
25
|
return ('Access denied (403) reading tenant-service configuration. This is more likely the wrong tenant realm ' +
|
|
19
26
|
'or environment than a missing role — check ADSP_TENANT_REALM and ADSP_ENV.');
|
|
20
27
|
}
|
|
@@ -52,6 +59,7 @@ always need explicit assignment regardless of that flag.
|
|
|
52
59
|
function createServiceRolesTools() {
|
|
53
60
|
return [
|
|
54
61
|
{
|
|
62
|
+
kind: 'live',
|
|
55
63
|
name: 'list_service_roles',
|
|
56
64
|
annotations: types_1.LIVE_TOOL_ANNOTATIONS,
|
|
57
65
|
description: 'List every ADSP platform service\'s registered RBAC role (role name, description, whether it is ' +
|
|
@@ -63,7 +71,8 @@ function createServiceRolesTools() {
|
|
|
63
71
|
'ADSP_CLIENT_ID and ADSP_CLIENT_SECRET environment variables for non-interactive/CI use.',
|
|
64
72
|
inputSchema: { type: 'object', properties: {} },
|
|
65
73
|
handler: (_args, context) => (0, liveToolLimit_1.withLiveToolPermit)(async () => {
|
|
66
|
-
const
|
|
74
|
+
const caller = context?.caller;
|
|
75
|
+
const tokenResult = caller ? { status: 'ok', token: caller.accessToken } : await (0, adsp_cli_1.getAccessToken)();
|
|
67
76
|
if (tokenResult.status === 'not-authenticated') {
|
|
68
77
|
(0, metrics_1.getMetrics)().recordUpstreamError('list_service_roles', 'not_authenticated');
|
|
69
78
|
return {
|
|
@@ -74,7 +83,7 @@ function createServiceRolesTools() {
|
|
|
74
83
|
};
|
|
75
84
|
}
|
|
76
85
|
try {
|
|
77
|
-
const directoryServiceUrl = (0, adsp_cli_1.getDirectoryServiceUrl)();
|
|
86
|
+
const directoryServiceUrl = caller ? caller.directoryServiceUrl : (0, adsp_cli_1.getDirectoryServiceUrl)();
|
|
78
87
|
const roles = await (0, adsp_cli_1.getServiceRoles)(tokenResult.token, directoryServiceUrl);
|
|
79
88
|
return {
|
|
80
89
|
content: [{ type: 'text', text: SERVICE_ROLES_PREAMBLE + JSON.stringify(roles, null, 2) }],
|
|
@@ -82,7 +91,7 @@ function createServiceRolesTools() {
|
|
|
82
91
|
}
|
|
83
92
|
catch (err) {
|
|
84
93
|
(0, metrics_1.getMetrics)().recordUpstreamError('list_service_roles', (0, upstreamErrors_1.classifyUpstreamError)(err));
|
|
85
|
-
return { isError: true, content: [{ type: 'text', text: describeError(err) }] };
|
|
94
|
+
return { isError: true, content: [{ type: 'text', text: describeError(err, caller !== undefined) }] };
|
|
86
95
|
}
|
|
87
96
|
}, context?.signal),
|
|
88
97
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerServiceRolesTool.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk-mcp-server/src/tools/registerServiceRolesTool.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"registerServiceRolesTool.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk-mcp-server/src/tools/registerServiceRolesTool.ts"],"names":[],"mappings":";;AAuEA,0DA2CC;AAlHD,8CAMyB;AACzB,wCAAwC;AACxC,mCAAoE;AACpE,mDAAqD;AACrD,qDAAkF;AAElF,SAAS,aAAa,CAAC,GAAY,EAAE,cAAuB;IAC1D,IAAI,GAAG,YAAY,qCAA0B,EAAE,CAAC;QAC9C,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;IAED,IAAI,GAAG,YAAY,2BAAgB,EAAE,CAAC;QACpC,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YACvB,IAAI,cAAc,EAAE,CAAC;gBACnB,OAAO,wCAAuB,CAAC;YACjC,CAAC;YACD,OAAO,uFAAuF,CAAC;QACjG,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YACvB,IAAI,cAAc,EAAE,CAAC;gBACnB,OAAO,CACL,uGAAuG;oBACvG,+DAA+D,CAChE,CAAC;YACJ,CAAC;YACD,OAAO,CACL,uGAAuG;gBACvG,4EAA4E,CAC7E,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC;YACtB,OAAO,wCAAwC,GAAG,CAAC,MAAM,0DAA0D,CAAC;QACtH,CAAC;QACD,OAAO,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AE;yBACxG;qBACF,CAAC;gBACJ,CAAC;gBAED,IAAI,CAAC;oBACH,MAAM,mBAAmB,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,IAAA,iCAAsB,GAAE,CAAC;oBAC3F,MAAM,KAAK,GAAG,MAAM,IAAA,0BAAe,EAAC,WAAW,CAAC,KAAK,EAAE,mBAAmB,CAAC,CAAC;oBAC5E,OAAO;wBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,sBAAsB,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;qBAC3F,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAA,oBAAU,GAAE,CAAC,mBAAmB,CAAC,oBAAoB,EAAE,IAAA,sCAAqB,EAAC,GAAG,CAAC,CAAC,CAAC;oBACnF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,GAAG,EAAE,MAAM,KAAK,SAAS,CAAC,EAAE,CAAC,EAAE,CAAC;gBACxG,CAAC;YACH,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC;SACtB;KACF,CAAC;AACJ,CAAC"}
|
package/src/tools/types.d.ts
CHANGED
|
@@ -4,9 +4,15 @@ export interface JsonSchemaObject {
|
|
|
4
4
|
properties?: Record<string, unknown>;
|
|
5
5
|
required?: string[];
|
|
6
6
|
}
|
|
7
|
+
export interface CallerSignIn {
|
|
8
|
+
accessToken: string;
|
|
9
|
+
directoryServiceUrl: string;
|
|
10
|
+
}
|
|
7
11
|
export interface ToolCallContext {
|
|
8
12
|
/** Aborted when the client cancels the call or disconnects. */
|
|
9
13
|
signal?: AbortSignal;
|
|
14
|
+
/** Set in hosted mode: live tools act as the signed-in caller instead of the local CLI login. */
|
|
15
|
+
caller?: CallerSignIn;
|
|
10
16
|
}
|
|
11
17
|
/**
|
|
12
18
|
* MCP tool annotations are hints for the client, not enforcement. Every tool here only reads, so all declare
|
|
@@ -38,7 +44,10 @@ export interface ToolDefinition {
|
|
|
38
44
|
*/
|
|
39
45
|
handler: (args: Record<string, unknown>, context?: ToolCallContext) => Promise<CallToolResult> | CallToolResult;
|
|
40
46
|
}
|
|
47
|
+
export declare function isOfflineTool(tool: ToolDefinition | LiveToolDefinition): tool is ToolDefinition;
|
|
41
48
|
export interface LiveToolDefinition {
|
|
49
|
+
/** Required, not inferred from annotations, because plain /mcp serves every tool that lacks it without sign-in. */
|
|
50
|
+
kind: 'live';
|
|
42
51
|
name: string;
|
|
43
52
|
description: string;
|
|
44
53
|
inputSchema: JsonSchemaObject;
|
package/src/tools/types.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.LIVE_TOOL_ANNOTATIONS = exports.OFFLINE_TOOL_ANNOTATIONS = void 0;
|
|
4
|
+
exports.isOfflineTool = isOfflineTool;
|
|
4
5
|
/**
|
|
5
6
|
* MCP tool annotations are hints for the client, not enforcement. Every tool here only reads, so all declare
|
|
6
7
|
* `readOnlyHint`. Offline tools answer from content bundled in the package, so they also declare a closed world;
|
|
@@ -8,4 +9,7 @@ exports.LIVE_TOOL_ANNOTATIONS = exports.OFFLINE_TOOL_ANNOTATIONS = void 0;
|
|
|
8
9
|
*/
|
|
9
10
|
exports.OFFLINE_TOOL_ANNOTATIONS = { readOnlyHint: true, openWorldHint: false };
|
|
10
11
|
exports.LIVE_TOOL_ANNOTATIONS = { readOnlyHint: true };
|
|
12
|
+
function isOfflineTool(tool) {
|
|
13
|
+
return !('kind' in tool);
|
|
14
|
+
}
|
|
11
15
|
//# sourceMappingURL=types.js.map
|
package/src/tools/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk-mcp-server/src/tools/types.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk-mcp-server/src/tools/types.ts"],"names":[],"mappings":";;;AA4CA,sCAEC;AA1BD;;;;GAIG;AACU,QAAA,wBAAwB,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAW,CAAC;AACjF,QAAA,qBAAqB,GAAG,EAAE,YAAY,EAAE,IAAI,EAAW,CAAC;AAkBrE,SAAgB,aAAa,CAAC,IAAyC;IACrE,OAAO,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC;AAC3B,CAAC"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CALLER_SIGN_IN_REJECTED = void 0;
|
|
3
4
|
exports.classifyUpstreamError = classifyUpstreamError;
|
|
4
5
|
const adsp_cli_1 = require("@abgov/adsp-cli");
|
|
6
|
+
exports.CALLER_SIGN_IN_REJECTED = 'Your sign-in was rejected or has expired. Sign in again from your MCP client.';
|
|
5
7
|
function classifyUpstreamError(err) {
|
|
6
8
|
if (err instanceof adsp_cli_1.ServiceNotInDirectoryError) {
|
|
7
9
|
return 'not_in_directory';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upstreamErrors.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk-mcp-server/src/tools/upstreamErrors.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"upstreamErrors.js","sourceRoot":"","sources":["../../../../../libs/adsp-sdk-mcp-server/src/tools/upstreamErrors.ts"],"names":[],"mappings":";;;AAMA,sDAYC;AAlBD,8CAA+E;AAGlE,QAAA,uBAAuB,GAClC,+EAA+E,CAAC;AAElF,SAAgB,qBAAqB,CAAC,GAAY;IAChD,IAAI,GAAG,YAAY,qCAA0B,EAAE,CAAC;QAC9C,OAAO,kBAAkB,CAAC;IAC5B,CAAC;IACD,IAAI,GAAG,YAAY,2BAAgB,EAAE,CAAC;QACpC,OAAO,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC;IACrD,CAAC;IACD,sEAAsE;IACtE,IAAI,GAAG,YAAY,SAAS,EAAE,CAAC;QAC7B,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
|