fa-mcp-sdk 0.11.8 → 0.11.12
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/cli-template/.env.example +48 -43
- package/cli-template/FA-MCP-SDK-DOC/00-FA-MCP-SDK-index.md +1 -1
- package/cli-template/FA-MCP-SDK-DOC/02-1-tools-and-api.md +86 -0
- package/cli-template/FA-MCP-SDK-DOC/06-utilities.md +62 -0
- package/cli-template/FA-MCP-SDK-DOC/12-implementation-standard.md +48 -3
- package/cli-template/package.json +1 -1
- package/package.json +1 -1
|
@@ -1,43 +1,48 @@
|
|
|
1
|
-
# SERVICE_NAME - service name. If this variable is not specified, it is taken from package.json.name
|
|
2
|
-
SERVICE_NAME={{project.name}}
|
|
3
|
-
# PRODUCT_NAME - If this variable is not specified, it is taken from package.json.productName
|
|
4
|
-
# PRODUCT_NAME=
|
|
5
|
-
|
|
6
|
-
NODE_ENV={{NODE_ENV}}
|
|
7
|
-
# Used for PM2
|
|
8
|
-
SERVICE_INSTANCE={{SERVICE_INSTANCE}}
|
|
9
|
-
PM2_NAMESPACE={{PM2_NAMESPACE}}
|
|
10
|
-
|
|
11
|
-
# Affects how the Consul service ID is formed - as a product or development ID
|
|
12
|
-
NODE_CONSUL_ENV={{NODE_CONSUL_ENV}}
|
|
13
|
-
|
|
14
|
-
DEBUG=config-info
|
|
15
|
-
# Used for PM2 service configuration
|
|
16
|
-
#┌────┬───────────────────────────────────────────────────────────┬─────────────────┬
|
|
17
|
-
#│ id │ name │ namespace │
|
|
18
|
-
#├────┼───────────────────────────────────────────────────────────┼─────────────────┼
|
|
19
|
-
#│ 1 │ <SERVICE_NAME | package.json.name>[--<SERVICE_INSTANCE>] │ <PM2_NAMESPACE> │
|
|
20
|
-
|
|
21
|
-
## DEBUG patterns ##
|
|
22
|
-
# AP-UPDATER - consul/access-points-updater
|
|
23
|
-
# fa-consul:reg | fa-consul:* - consul/cyclic-register
|
|
24
|
-
# fa-consul:curl - consul/prepare-consul-api
|
|
25
|
-
# token:auth
|
|
26
|
-
# mcp:tool
|
|
27
|
-
# mcp:resource
|
|
28
|
-
# mcp:notification
|
|
29
|
-
# mcp:prompt
|
|
30
|
-
# mcp:*
|
|
31
|
-
#
|
|
32
|
-
#
|
|
33
|
-
#
|
|
34
|
-
#
|
|
35
|
-
#
|
|
36
|
-
#
|
|
37
|
-
#
|
|
38
|
-
|
|
39
|
-
#
|
|
40
|
-
#
|
|
41
|
-
|
|
42
|
-
#
|
|
43
|
-
|
|
1
|
+
# SERVICE_NAME - service name. If this variable is not specified, it is taken from package.json.name
|
|
2
|
+
SERVICE_NAME={{project.name}}
|
|
3
|
+
# PRODUCT_NAME - If this variable is not specified, it is taken from package.json.productName
|
|
4
|
+
# PRODUCT_NAME=
|
|
5
|
+
|
|
6
|
+
NODE_ENV={{NODE_ENV}}
|
|
7
|
+
# Used for PM2
|
|
8
|
+
SERVICE_INSTANCE={{SERVICE_INSTANCE}}
|
|
9
|
+
PM2_NAMESPACE={{PM2_NAMESPACE}}
|
|
10
|
+
|
|
11
|
+
# Affects how the Consul service ID is formed - as a product or development ID
|
|
12
|
+
NODE_CONSUL_ENV={{NODE_CONSUL_ENV}}
|
|
13
|
+
|
|
14
|
+
DEBUG=config-info
|
|
15
|
+
# Used for PM2 service configuration
|
|
16
|
+
#┌────┬───────────────────────────────────────────────────────────┬─────────────────┬
|
|
17
|
+
#│ id │ name │ namespace │
|
|
18
|
+
#├────┼───────────────────────────────────────────────────────────┼─────────────────┼
|
|
19
|
+
#│ 1 │ <SERVICE_NAME | package.json.name>[--<SERVICE_INSTANCE>] │ <PM2_NAMESPACE> │
|
|
20
|
+
|
|
21
|
+
## DEBUG patterns ##
|
|
22
|
+
# AP-UPDATER - consul/access-points-updater
|
|
23
|
+
# fa-consul:reg | fa-consul:* - consul/cyclic-register
|
|
24
|
+
# fa-consul:curl - consul/prepare-consul-api
|
|
25
|
+
# token:auth - authentication: which auth method matched, token parsing/validation outcome
|
|
26
|
+
# mcp:tool - tools/call: tool name + arguments in, response (text or JSON) out
|
|
27
|
+
# mcp:resource - resources/list and resources/read: URI in, body out
|
|
28
|
+
# mcp:notification - all incoming notifications/* (method + params)
|
|
29
|
+
# mcp:prompt - prompts/list and prompts/get: name/args in, messages out
|
|
30
|
+
# mcp:* - all four MCP channels above at once
|
|
31
|
+
# mcp-handshake - HTTP transport: per-request dump (method, id, session routing, protocol, auth, IP)
|
|
32
|
+
# mcp-rpc - HTTP transport: one-line summary of every successful JSON-RPC response
|
|
33
|
+
#
|
|
34
|
+
#(session-lifecycle events, the -32600 "no valid session" rejection and JSON-RPC errors log always)
|
|
35
|
+
#
|
|
36
|
+
# ========================================================================
|
|
37
|
+
# AGENT TESTER - Built-in AI agent for testing MCP tools
|
|
38
|
+
# ========================================================================
|
|
39
|
+
# AGENT_TESTER_ENABLED=true
|
|
40
|
+
# AGENT_TESTER_USE_AUTH=false
|
|
41
|
+
# AGENT_TESTER_OPENAI_API_KEY=sk-...
|
|
42
|
+
# AGENT_TESTER_OPENAI_BASE_URL=
|
|
43
|
+
|
|
44
|
+
# The address of the mcp server for testing. Default: http://localhost:<config.webServer.port>
|
|
45
|
+
# TEST_MCP_SERVER_URL=
|
|
46
|
+
|
|
47
|
+
# The directory to store test result logs
|
|
48
|
+
TEST_RESULT_LOGS_DIR='_logs/mcp'
|
|
@@ -18,7 +18,7 @@ npm install fa-mcp-sdk
|
|
|
18
18
|
| [03-configuration](03-configuration.md) | `appConfig`, YAML config, access points, cache, **`mcp.limits` (payload/result/timeout)**, **`mcp.pagination`**, **`mcp.resources` (MAY)**, **`mcp.rateLimit.scope` + `maxConcurrentPerSubject` (§14)**, **`webServer.trustProxy`**, **`webServer.tokenCheck.allowQueryToken` (§7.1)**, **/health & /ready**, **CORS hardening**, **MCP error codes** (`-32002…-32005`) | Server configuration, external services, transport-level hardening |
|
|
19
19
|
| [04-authentication](04-authentication.md) | JWT (**4 modes: legacyAesCtr / embedded / localKey / remoteJwks**), Basic auth, server tokens, **OAuth discovery + `/oauth/token` + JWKS**, **`requiredScopes` enforcement (§7.5)**, **`WWW-Authenticate` realm + invalid_token (§7.4)**, **HTTP 403 `forbidden` flag**, `createAuthMW()`, Token Generator, CLI Token Generator (mode-aware), JWT Generation API | Authentication setup |
|
|
20
20
|
| [05-ad-authorization](05-ad-authorization.md) | AD group authorization at HTTP/tool levels | AD group restrictions |
|
|
21
|
-
| [06-utilities](06-utilities.md) | `ServerError`, `normalizeHeaders`, logging, MCP debug switches (`DEBUG=mcp:*`), JSON-lines sink (`mcp.debug.logFile` → `emitTrace`), built-in debug tools (`mcp.debug.builtinTools`), Consul, graceful shutdown | Error handling, utilities, request tracing, post-mortem analysis |
|
|
21
|
+
| [06-utilities](06-utilities.md) | `ServerError`, `normalizeHeaders`, logging, MCP debug switches (`DEBUG=mcp:*`), **HTTP connection & RPC tracing (`DEBUG=mcp-handshake` / `mcp-rpc`, always-on session-lifecycle + `-32600` + error logging)**, JSON-lines sink (`mcp.debug.logFile` → `emitTrace`), built-in debug tools (`mcp.debug.builtinTools`), Consul, graceful shutdown | Error handling, utilities, request tracing, post-mortem analysis |
|
|
22
22
|
| [07-testing-and-operations](07-testing-and-operations.md) | Test clients (STDIO, HTTP, SSE, Streamable HTTP); universal `debug-tool` fixture covering every `CallToolResult` shape | Testing, deployment, exercising client code against image/audio/resource/error/delay variants |
|
|
23
23
|
| [08-agent-tester-and-headless-api](08-agent-tester-and-headless-api.md) | Agent Tester, Headless API, structured logging, automated testing, UI `data-testid` reference. **MCP Apps mode**: capability negotiation, `appCalls[]` / `app_calls[]`, widget iframe bridge, App Inspector tab | Agent-driven tool development, CLI automation, UI E2E tests, MCP Apps host for development |
|
|
24
24
|
| [09-database](09-database.md) | PostgreSQL sugar layer (`queryMAIN`, `execMAIN`, `getInsertSqlMAIN`, `getMergeSqlMAIN`, `mergeByBatch`), `pgvector`, secondary DBs | Database access, upserts, batching |
|
|
@@ -172,6 +172,92 @@ asJsonError({ code: 'NOT_FOUND', key: 'X' }); // { structuredContent: {...},
|
|
|
172
172
|
> for missing resources, convert those branches to `return formatToolError('Not found: ...')`. The
|
|
173
173
|
> LLM will start surfacing "Such an issue does not exist" to the user instead of failing the call.
|
|
174
174
|
|
|
175
|
+
### Normalizing upstream API errors
|
|
176
|
+
|
|
177
|
+
The `isError` vs `throw` decision above is easy when the handler discovers the problem itself (a `null`
|
|
178
|
+
issue). It is harder when the failure surfaces as a raw error thrown deep inside an HTTP client — a 404
|
|
179
|
+
from the upstream API arrives as an Axios/`fetch` rejection, not as a clean `formatToolError`. Catching
|
|
180
|
+
that in every handler is repetitive and easy to get wrong. The pattern below centralizes it in the single
|
|
181
|
+
`catch` of `handleToolCall`, and implements standard
|
|
182
|
+
[§13.4 "Mapping upstream errors"](./12-implementation-standard.md#134-mapping-upstream-downstream-api-errors).
|
|
183
|
+
|
|
184
|
+
It has three pure steps — translate, classify, surface:
|
|
185
|
+
|
|
186
|
+
```typescript
|
|
187
|
+
import {
|
|
188
|
+
formatToolError, ToolExecutionError, ServerError, RateLimitedError,
|
|
189
|
+
UpstreamUnavailableError, ValidationError, ConflictError, ResourceNotFoundError, toStr,
|
|
190
|
+
} from 'fa-mcp-sdk';
|
|
191
|
+
|
|
192
|
+
// 1. TRANSLATE — convert a raw upstream HTTP error into a typed error class (no throw here).
|
|
193
|
+
// Map the upstream status onto the Appendix B error set instead of one opaque ServerError.
|
|
194
|
+
function handleAxiosError(error: any, toolName: string): never {
|
|
195
|
+
const status = error?.response?.status;
|
|
196
|
+
const msg = extractUpstreamMessage(error?.response?.data) ?? error?.message ?? 'Unknown error';
|
|
197
|
+
const data = { toolName, status }; // safe: no body, no headers, no stack
|
|
198
|
+
|
|
199
|
+
if (!status || status >= 502) throw new UpstreamUnavailableError(`Upstream unavailable: ${msg}`, data);
|
|
200
|
+
if (status === 400) throw new ValidationError(`Invalid request: ${msg}`);
|
|
201
|
+
if (status === 404) throw new ResourceNotFoundError(msg, data);
|
|
202
|
+
if (status === 409) throw new ConflictError(`State conflict: ${msg}`, data);
|
|
203
|
+
if (status === 429) {
|
|
204
|
+
const retryAfter = parseInt(error?.response?.headers?.['retry-after'], 10) || 60;
|
|
205
|
+
throw new RateLimitedError(`Rate limited: ${msg}`, retryAfter);
|
|
206
|
+
}
|
|
207
|
+
// 401/403 and other 5xx — keep the upstream status in `data.status` so step 2 can recognize it.
|
|
208
|
+
throw new ServerError(`Upstream error (HTTP ${status}): ${msg}`, data);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// 2. NORMALIZE — turn ANY thrown value into a concrete Error, still WITHOUT throwing.
|
|
212
|
+
// A pure function lets the MCP path (may surface to the LLM) and a REST path (always throws)
|
|
213
|
+
// share one step.
|
|
214
|
+
export function normalizeToolError(error: any, toolName: string): Error {
|
|
215
|
+
if (error instanceof ToolExecutionError || error instanceof ServerError ||
|
|
216
|
+
typeof error?.jsonRpcCode === 'number') {
|
|
217
|
+
return error; // already a domain error
|
|
218
|
+
}
|
|
219
|
+
if (isAxiosError(error)) {
|
|
220
|
+
try { handleAxiosError(error, toolName); } catch (converted) { return converted as Error; }
|
|
221
|
+
}
|
|
222
|
+
return new ServerError(toStr(error), { toolName }, true); // catch-all, sanitized (no upstream status)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// 3. CLASSIFY — decide whether the model should SEE the message (isError) or get a thrown protocol error.
|
|
226
|
+
export function isLlmVisibleError(error: any): boolean {
|
|
227
|
+
if (error instanceof RateLimitedError) return false; // retry contract — keep -32003 thrown
|
|
228
|
+
if (error instanceof ToolExecutionError) return true; // JQL/validation written for the model
|
|
229
|
+
if (typeof error?.jsonRpcCode === 'number') return true; // ValidationError/NotFound/Conflict/Upstream
|
|
230
|
+
if (error instanceof ServerError && error?.details?.status != null) return true; // upstream 401/403/5xx
|
|
231
|
+
return false; // catch-all ServerError → "Internal error"
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Wire all three into the single `catch`, so every handler benefits without its own try/catch:
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
} catch (error: any) {
|
|
239
|
+
const normalized = normalizeToolError(error, toolName);
|
|
240
|
+
if (isLlmVisibleError(normalized)) {
|
|
241
|
+
// The model reads the upstream reason ("Issue AITECH-123 does not exist") and self-corrects.
|
|
242
|
+
return formatToolError(normalized.message);
|
|
243
|
+
}
|
|
244
|
+
throw normalized; // RateLimitedError / internal → protocol error
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Why this split matters:
|
|
249
|
+
|
|
250
|
+
- A **404 raised by the upstream API** becomes `ResourceNotFoundError` (numeric `jsonRpcCode`), so
|
|
251
|
+
`isLlmVisibleError` returns `true` and the model gets `result.isError=true` — exactly like the manual
|
|
252
|
+
`formatToolError` branch in the previous section, but for an error it never saw directly.
|
|
253
|
+
- **`RateLimitedError` stays thrown** as `-32003` with `retryAfter` — clients depend on that contract, so
|
|
254
|
+
it must not collapse into an `isError` text result.
|
|
255
|
+
- A **catch-all `ServerError`** (no `details.status`) stays thrown and is sanitized by the SDK to
|
|
256
|
+
`Internal error` — its text may carry internal detail and MUST NOT reach the model (standard §13.3).
|
|
257
|
+
|
|
258
|
+
> Keep `normalizeToolError` **pure** (never throws). A throwing normalizer forces every call site into its
|
|
259
|
+
> own try/catch and defeats the point of centralizing the logic.
|
|
260
|
+
|
|
175
261
|
### Headers Access
|
|
176
262
|
|
|
177
263
|
Headers are normalized to lowercase. Available in HTTP/SSE transports:
|
|
@@ -37,6 +37,26 @@ class MyError extends BaseMcpError {
|
|
|
37
37
|
| `RateLimitedError` | `RATE_LIMITED` | `-32003` | 429 | Appendix B |
|
|
38
38
|
| `TimeoutError` | `TIMEOUT` | `-32004` | 504 | Appendix B |
|
|
39
39
|
| `PayloadTooLargeError` | `PAYLOAD_TOO_LARGE` | `-32005` | 413 | Appendix B |
|
|
40
|
+
| `UpstreamUnavailableError` | `UPSTREAM_UNAVAILABLE` | `-32006` | 503 | Appendix B |
|
|
41
|
+
| `ConflictError` | `CONFLICT` | `-32007` | 409 | Appendix B |
|
|
42
|
+
|
|
43
|
+
### Mapping a Downstream API Status to a Typed Error
|
|
44
|
+
|
|
45
|
+
When a tool proxies a downstream HTTP API, translate the upstream status into one of these classes instead
|
|
46
|
+
of a single opaque `ServerError`. This gives the JSON-RPC layer a meaningful code and lets the surfacing
|
|
47
|
+
logic (next) decide whether the model should see the message. This is standard §13.4; the end-to-end
|
|
48
|
+
`normalizeToolError` / `isLlmVisibleError` / `formatToolError` pattern is in
|
|
49
|
+
[02-1-tools-and-api.md → "Normalizing upstream API errors"](./02-1-tools-and-api.md).
|
|
50
|
+
|
|
51
|
+
| Upstream HTTP | Throw | Surfaced to model as `isError`? |
|
|
52
|
+
|-------------------------------|-----------------------------|---------------------------------|
|
|
53
|
+
| 400 | `ValidationError` | yes |
|
|
54
|
+
| 401 / 403 | `ServerError` (status in data) | yes |
|
|
55
|
+
| 404 | `ResourceNotFoundError` | yes |
|
|
56
|
+
| 409 | `ConflictError` | yes |
|
|
57
|
+
| 429 | `RateLimitedError` | no — thrown, keeps `retryAfter` |
|
|
58
|
+
| 502 / 503 / 504 / no response | `UpstreamUnavailableError` | yes |
|
|
59
|
+
| other 5xx / unexpected | `ServerError` (no status) | no — thrown, sanitized |
|
|
40
60
|
|
|
41
61
|
## Error Utilities
|
|
42
62
|
|
|
@@ -336,6 +356,48 @@ echo "DEBUG=mcp:tool,mcp:resource" >> .env
|
|
|
336
356
|
> `stdout` via `console.log`, so enabling `DEBUG=mcp:*` in STDIO mode **will corrupt the framing**
|
|
337
357
|
> the client sees. Use these switches with HTTP/SSE transport, or redirect stdout.
|
|
338
358
|
|
|
359
|
+
## HTTP Connection & RPC Tracing (`DEBUG=mcp-handshake`, `DEBUG=mcp-rpc`)
|
|
360
|
+
|
|
361
|
+
Separate from the `mcp:*` channel switches above, the **Streamable HTTP transport** carries its own
|
|
362
|
+
connection- and response-level tracing in `web/server-http.ts`. These switches use hyphenated names
|
|
363
|
+
(`mcp-handshake`, `mcp-rpc`) and are read straight from the comma-split `DEBUG` env var — they do
|
|
364
|
+
**not** go through the `af-tools-ts` `Debug()` machinery, so they are not covered by `mcp:*` or `*`.
|
|
365
|
+
List them explicitly, e.g. `DEBUG=mcp-handshake,mcp-rpc`. They exist to answer the two questions the
|
|
366
|
+
`mcp:*` taps cannot: *why did the client get a session/protocol error?* and *what did the server
|
|
367
|
+
actually send back?*
|
|
368
|
+
|
|
369
|
+
| Env value | What it logs |
|
|
370
|
+
|-----------------------|---------------------------------------------------------------------------------------|
|
|
371
|
+
| *(always on)* | Session created / closed / transport-closed (with active-session count); the `-32600` "no valid session" rejection with the reason. |
|
|
372
|
+
| `DEBUG=mcp-handshake` | Per-request dump for every `/mcp` call: JSON-RPC method + id, short session id, routing hit/miss, protocol version, `Accept` / `Content-Type`, whether an auth header is present, and client IP. |
|
|
373
|
+
| `DEBUG=mcp-rpc` | One-line summary of every **successful** JSON-RPC response (status, ids, `result=ok` / notifications). |
|
|
374
|
+
|
|
375
|
+
Two things always log regardless of the switches, because they are otherwise silent failure modes:
|
|
376
|
+
|
|
377
|
+
- **The `-32600` rejection.** When a request reaches `/mcp` without a valid session and is not an
|
|
378
|
+
`initialize`, the server now logs *why* — the client must send `initialize` first or echo a valid
|
|
379
|
+
`mcp-session-id` header — and notes when the supplied session id is unknown or expired (with the
|
|
380
|
+
count of known sessions). This is the trace to look for when the client reports `-32600` but the
|
|
381
|
+
server log was previously empty.
|
|
382
|
+
- **Every JSON-RPC error response.** A response tee on `POST /mcp` and the `GET`/`DELETE` session
|
|
383
|
+
routes captures the outgoing body, parses it (auto-detecting a plain `application/json` answer vs.
|
|
384
|
+
the `data:` frames of an SSE stream), and logs each error's HTTP status, request id, `code`,
|
|
385
|
+
`message`, and truncated `data`, together with the originating request summary. The capture is
|
|
386
|
+
capped at 256 KB per response so a long SSE stream cannot exhaust memory (`[capture truncated]`
|
|
387
|
+
marks a hit), and the trace is wrapped so it can never break the real response.
|
|
388
|
+
|
|
389
|
+
```bash
|
|
390
|
+
# Why is the client getting "no valid session" / -32600? (handshake dump on every request)
|
|
391
|
+
DEBUG=mcp-handshake yarn start
|
|
392
|
+
|
|
393
|
+
# Also summarise successful responses (otherwise only errors are logged)
|
|
394
|
+
DEBUG=mcp-handshake,mcp-rpc yarn start
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
> These switches are HTTP-transport only — STDIO never opens sessions, so they have no effect there.
|
|
398
|
+
> They are safe to leave off in production; the always-on session-lifecycle and error lines are the
|
|
399
|
+
> ones worth keeping in normal operation.
|
|
400
|
+
|
|
339
401
|
### Extending with Custom Debug Categories
|
|
340
402
|
|
|
341
403
|
Add your own switches with the same `Debug()` helper from `af-tools-ts`:
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
| Parameter | Value |
|
|
4
4
|
|----------------------------|------------------------------------|
|
|
5
|
-
| Version | 1.
|
|
5
|
+
| Version | 1.3 |
|
|
6
6
|
| Status | Active |
|
|
7
|
-
| Date | 2026-06-
|
|
7
|
+
| Date | 2026-06-05 |
|
|
8
8
|
| Scope | All internal company MCP servers |
|
|
9
9
|
| Base MCP | MCP 2025-11-25 |
|
|
10
10
|
| Starter SDK (optional) | `fa-mcp-sdk` |
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
> This document is the English translation of the corporate implementation standard. It restates the
|
|
14
14
|
> explicit MCP 2025-11-25 requirements plus the corporate Avatar / AI Platform profile in a single
|
|
15
15
|
> self-contained document. Version 1.2 adds the side-effect tools and risk-level rules and fixes the
|
|
16
|
-
> `-32007` error-code inconsistency.
|
|
16
|
+
> `-32007` error-code inconsistency. Version 1.3 adds §13.4 on mapping upstream (downstream API) errors
|
|
17
|
+
> to typed error classes and the rule for surfacing model-correctable errors via `result.isError=true`.
|
|
17
18
|
|
|
18
19
|
## Table of Contents
|
|
19
20
|
|
|
@@ -765,6 +766,50 @@ An error returned externally MUST NOT contain:
|
|
|
765
766
|
- raw SQL/expression text with user data;
|
|
766
767
|
- internal service names that are not part of the public contract.
|
|
767
768
|
|
|
769
|
+
### 13.4. Mapping upstream (downstream API) errors
|
|
770
|
+
|
|
771
|
+
This section is a corporate recommendation for servers that proxy a downstream HTTP API (Jira, GitLab, an
|
|
772
|
+
internal microservice, etc.). It defines how a failed upstream call is translated into the two error types
|
|
773
|
+
of §13.1 so that the model receives an actionable reason instead of one opaque `-32603 Internal error`.
|
|
774
|
+
|
|
775
|
+
When a tool calls a downstream API, the server SHOULD translate the upstream HTTP status into the matching
|
|
776
|
+
typed error class from [Appendix B](#appendix-b-error-codes) rather than collapsing every failure into a
|
|
777
|
+
generic internal error. The recommended mapping is:
|
|
778
|
+
|
|
779
|
+
| Upstream HTTP | Typed error class | JSON-RPC | Returned to the model |
|
|
780
|
+
| --------------------------------- | ---------------------- | -------- | --------------------- |
|
|
781
|
+
| 400 | `ValidationError` | -32602 | `isError=true` |
|
|
782
|
+
| 401 / 403 | `ServerError` (with upstream status in `data`) | -32000 | `isError=true` |
|
|
783
|
+
| 404 | `ResourceNotFoundError`| -32002 | `isError=true` |
|
|
784
|
+
| 409 | `ConflictError` | -32007 | `isError=true` |
|
|
785
|
+
| 429 | `RateLimitedError` | -32003 | thrown (see below) |
|
|
786
|
+
| 502 / 503 / 504 / no response | `UpstreamUnavailableError` | -32006 | `isError=true` |
|
|
787
|
+
| other 5xx | `ServerError` | -32000 | thrown |
|
|
788
|
+
|
|
789
|
+
The decision whether to surface an error to the model or to throw it follows three rules:
|
|
790
|
+
|
|
791
|
+
- An error whose message is **safe to expose and actionable** — built from the structured upstream error
|
|
792
|
+
body, not from internal state — SHOULD be returned as a tool execution result with `result.isError=true`
|
|
793
|
+
(§9.4, §13.1). The model reads the upstream reason (for example `Issue AITECH-123 does not exist`) and
|
|
794
|
+
self-corrects instead of treating the call as a hard sandbox failure. A `404` raised by the downstream
|
|
795
|
+
API is the canonical case: it MUST reach the model as `result.isError=true`, not as a thrown protocol
|
|
796
|
+
error.
|
|
797
|
+
- `-32003 Rate limited` MUST remain a **thrown** protocol error and MUST carry the `Retry-After` header /
|
|
798
|
+
`retryAfter` value (§14, Appendix B.3). It MUST NOT be flattened into an `isError` text result, because
|
|
799
|
+
clients rely on the numeric code and the retry hint to schedule a retry.
|
|
800
|
+
- An internal failure with **no upstream status** (the catch-all wrapper around an unexpected exception)
|
|
801
|
+
MUST stay a thrown protocol error and MUST be sanitized per §13.3 — typically `-32603 Internal error`
|
|
802
|
+
with no stack trace and no secrets.
|
|
803
|
+
|
|
804
|
+
A reference implementation of this pattern — a pure `normalizeToolError()` that converts any thrown value
|
|
805
|
+
into a typed error without throwing, an `isLlmVisibleError()` predicate that applies the three rules above,
|
|
806
|
+
and the `formatToolError()` call that surfaces the message — is documented in
|
|
807
|
+
[02-1-tools-and-api.md → "Normalizing upstream API errors"](./02-1-tools-and-api.md).
|
|
808
|
+
|
|
809
|
+
Whatever message is exposed (via `isError=true` or a thrown error) MUST still satisfy the §13.3
|
|
810
|
+
prohibitions: the upstream error body is forwarded only after it has been reduced to its human-readable
|
|
811
|
+
text, never as a raw payload that could carry internal paths, tokens, or stack traces.
|
|
812
|
+
|
|
768
813
|
## 14. Limits and protection
|
|
769
814
|
|
|
770
815
|
Each server MUST document and enforce:
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fa-mcp-sdk",
|
|
3
3
|
"productName": "FA MCP SDK",
|
|
4
|
-
"version": "0.11.
|
|
4
|
+
"version": "0.11.12",
|
|
5
5
|
"description": "Core infrastructure and templates for building Model Context Protocol (MCP) servers with TypeScript",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/core/index.js",
|