fa-mcp-sdk 0.11.10 → 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.
@@ -1,48 +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 - 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'
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'
@@ -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
 
@@ -2,9 +2,9 @@
2
2
 
3
3
  | Parameter | Value |
4
4
  |----------------------------|------------------------------------|
5
- | Version | 1.2 |
5
+ | Version | 1.3 |
6
6
  | Status | Active |
7
- | Date | 2026-06-03 |
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:
@@ -58,7 +58,7 @@
58
58
  "dependencies": {
59
59
  "@modelcontextprotocol/sdk": "^1.29.0",
60
60
  "dotenv": "^17.4.1",
61
- "fa-mcp-sdk": "^0.11.10"
61
+ "fa-mcp-sdk": "^0.11.12"
62
62
  },
63
63
  "devDependencies": {
64
64
  "@types/express": "^5.0.6",
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.10",
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",