@yawlabs/mcp-compliance 0.5.0 → 0.7.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.
@@ -56,7 +56,7 @@ function computeScore(tests) {
56
56
 
57
57
  // src/types.ts
58
58
  var TEST_DEFINITIONS = [
59
- // ── Transport (10 tests) ─────────────────────────────────────────
59
+ // ── Transport (13 tests) ─────────────────────────────────────────
60
60
  {
61
61
  id: "transport-post",
62
62
  name: "HTTP POST accepted",
@@ -81,8 +81,8 @@ var TEST_DEFINITIONS = [
81
81
  category: "transport",
82
82
  required: false,
83
83
  specRef: "basic/transports#streamable-http",
84
- description: "Verifies that sending a JSON-RPC notification (no id field) returns HTTP 202 Accepted with no body. Per spec, servers MUST return 202 for notifications.",
85
- recommendation: "Detect JSON-RPC messages without an id field and return HTTP 202 with an empty body. Do not attempt to send a JSON-RPC response for notifications."
84
+ description: "Verifies that sending a JSON-RPC notification (no id field) returns exactly HTTP 202 Accepted with no body. Per spec, servers MUST return 202 \u2014 not 200 or 204.",
85
+ recommendation: "Detect JSON-RPC messages without an id field and return HTTP 202 with an empty body. Do not return 200 or 204 \u2014 the spec requires exactly 202 Accepted."
86
86
  },
87
87
  {
88
88
  id: "transport-session-id",
@@ -93,6 +93,24 @@ var TEST_DEFINITIONS = [
93
93
  description: "Tests that the server returns HTTP 400 when MCP-Session-Id header is missing on requests after initialization (when the server issued a session ID).",
94
94
  recommendation: "If your server issues an MCP-Session-Id header in the initialize response, reject subsequent requests that omit this header with HTTP 400."
95
95
  },
96
+ {
97
+ id: "transport-session-invalid",
98
+ name: "Returns 404 for unknown session ID",
99
+ category: "transport",
100
+ required: false,
101
+ specRef: "basic/transports#streamable-http",
102
+ description: "Sends a request with a fabricated MCP-Session-Id and verifies the server returns HTTP 404. Per spec, servers managing sessions MUST return 404 for unrecognized session IDs.",
103
+ recommendation: "Return HTTP 404 (Not Found) for requests with an MCP-Session-Id that does not match any active session. Do not return 400 \u2014 that is for missing session IDs."
104
+ },
105
+ {
106
+ id: "transport-content-type-reject",
107
+ name: "Rejects non-JSON request Content-Type",
108
+ category: "transport",
109
+ required: false,
110
+ specRef: "basic/transports#streamable-http",
111
+ description: "Sends a POST with Content-Type: text/plain instead of application/json and verifies the server rejects it with a 4xx status.",
112
+ recommendation: "Validate the Content-Type header on incoming POST requests. Reject requests that are not application/json with HTTP 415 (Unsupported Media Type) or 400."
113
+ },
96
114
  {
97
115
  id: "transport-get",
98
116
  name: "GET returns SSE stream or 405",
@@ -147,7 +165,16 @@ var TEST_DEFINITIONS = [
147
165
  description: "Sends multiple JSON-RPC requests in parallel and verifies the server responds to all with correct matching IDs. Tests that the server can handle concurrent connections.",
148
166
  recommendation: "Ensure your server can handle multiple simultaneous requests. Each response must include the correct id matching the request. Use async handlers or connection pooling."
149
167
  },
150
- // ── Lifecycle (12 tests) ─────────────────────────────────────────
168
+ {
169
+ id: "transport-sse-event-field",
170
+ name: "SSE responses include event: message",
171
+ category: "transport",
172
+ required: false,
173
+ specRef: "basic/transports#streamable-http",
174
+ description: "Sends a request with Accept: text/event-stream and checks that SSE responses include the event: message field. Per spec, servers MUST set event: message for JSON-RPC messages in SSE streams.",
175
+ recommendation: 'Include "event: message" before each "data:" line in your SSE responses. This is required by the MCP spec for JSON-RPC messages sent over SSE.'
176
+ },
177
+ // ── Lifecycle (15 tests) ─────────────────────────────────────────
151
178
  {
152
179
  id: "lifecycle-init",
153
180
  name: "Initialize handshake",
@@ -220,6 +247,33 @@ var TEST_DEFINITIONS = [
220
247
  description: "Verifies that the JSON-RPC response id matches the request id sent by the client. This is a fundamental JSON-RPC 2.0 requirement.",
221
248
  recommendation: "Copy the id field from the request into the response. This is a core JSON-RPC 2.0 requirement. Check that your framework does not modify or discard the request ID."
222
249
  },
250
+ {
251
+ id: "lifecycle-string-id",
252
+ name: "Supports string request IDs",
253
+ category: "lifecycle",
254
+ required: false,
255
+ specRef: "basic",
256
+ description: "Sends a request with a string id instead of a number. JSON-RPC 2.0 allows both string and number IDs. The server must echo back the exact string id in the response.",
257
+ recommendation: "Ensure your JSON-RPC implementation supports both string and number request IDs. Echo the id back exactly as received, preserving its type."
258
+ },
259
+ {
260
+ id: "lifecycle-version-negotiate",
261
+ name: "Handles unknown protocol version",
262
+ category: "lifecycle",
263
+ required: false,
264
+ specRef: "basic/lifecycle#version-negotiation",
265
+ description: 'Sends an initialize request with a future protocol version ("2099-01-01") and verifies the server either negotiates down to a version it supports or returns an error.',
266
+ recommendation: "When the client requests an unsupported protocol version, respond with the closest version your server supports. Do not blindly accept unknown versions."
267
+ },
268
+ {
269
+ id: "lifecycle-reinit-reject",
270
+ name: "Rejects second initialize request",
271
+ category: "lifecycle",
272
+ required: false,
273
+ specRef: "basic/lifecycle#initialization",
274
+ description: "Sends a second initialize request within the same session. Per spec, the client MUST NOT send initialize more than once. The server should reject it.",
275
+ recommendation: "Track initialization state per session. Reject duplicate initialize requests with a JSON-RPC error or HTTP 4xx. Do not reset session state on re-initialization."
276
+ },
223
277
  {
224
278
  id: "lifecycle-logging",
225
279
  name: "logging/setLevel accepted",
@@ -249,12 +303,12 @@ var TEST_DEFINITIONS = [
249
303
  },
250
304
  {
251
305
  id: "lifecycle-progress",
252
- name: "Accepts progress notifications",
306
+ name: "Handles progress notifications gracefully",
253
307
  category: "lifecycle",
254
308
  required: false,
255
309
  specRef: "basic/utilities#progress",
256
- description: "Tests that the server accepts notifications/progress without error. Servers should handle progress notifications for request tracking.",
257
- recommendation: "Accept notifications/progress with progressToken, progress, and optional total fields. Ignore notifications for unknown progress tokens."
310
+ description: "Sends a notifications/progress to the server and verifies it does not error. Note: per spec, progress flows from server to client during long-running requests. This test validates the server handles unexpected notifications gracefully.",
311
+ recommendation: "Accept unknown notifications without returning an error. The server should not crash or return a non-2xx status for notifications it does not recognize."
258
312
  },
259
313
  // ── Tools (4 tests) ──────────────────────────────────────────────
260
314
  {
@@ -263,7 +317,7 @@ var TEST_DEFINITIONS = [
263
317
  category: "tools",
264
318
  required: false,
265
319
  specRef: "server/tools#listing-tools",
266
- description: "Calls tools/list and validates it returns an array of tool definitions. Required if the server declares tools capability.",
320
+ description: "Calls tools/list and validates it returns an array of tool definitions. Dynamically required at runtime if the server declares tools capability.",
267
321
  recommendation: "Implement the tools/list handler to return { tools: [...] } with an array of tool definition objects. Each tool needs at least a name and inputSchema."
268
322
  },
269
323
  {
@@ -300,7 +354,7 @@ var TEST_DEFINITIONS = [
300
354
  category: "resources",
301
355
  required: false,
302
356
  specRef: "server/resources#listing-resources",
303
- description: "Calls resources/list and validates it returns an array. Required if the server declares resources capability.",
357
+ description: "Calls resources/list and validates it returns an array. Dynamically required at runtime if the server declares resources capability.",
304
358
  recommendation: "Implement resources/list to return { resources: [...] } with an array of resource objects. Each resource needs at least a uri and name."
305
359
  },
306
360
  {
@@ -346,7 +400,7 @@ var TEST_DEFINITIONS = [
346
400
  category: "prompts",
347
401
  required: false,
348
402
  specRef: "server/prompts#listing-prompts",
349
- description: "Calls prompts/list and validates it returns an array. Required if the server declares prompts capability.",
403
+ description: "Calls prompts/list and validates it returns an array. Dynamically required at runtime if the server declares prompts capability.",
350
404
  recommendation: "Implement prompts/list to return { prompts: [...] } with an array of prompt objects. Each prompt needs at least a name field."
351
405
  },
352
406
  {
@@ -367,7 +421,7 @@ var TEST_DEFINITIONS = [
367
421
  description: "Tests cursor-based pagination on prompts/list. Validates nextCursor is a string if present and that fetching the next page works.",
368
422
  recommendation: "If you return nextCursor in prompts/list, ensure it is a string and that passing it back as cursor in the next request returns valid results."
369
423
  },
370
- // ── Error Handling (8 tests) ─────────────────────────────────────
424
+ // ── Error Handling (10 tests) ────────────────────────────────────
371
425
  {
372
426
  id: "error-unknown-method",
373
427
  name: "Returns JSON-RPC error for unknown method",
@@ -440,6 +494,24 @@ var TEST_DEFINITIONS = [
440
494
  description: "Calls tools/call with a nonexistent tool name and verifies the server returns an error response.",
441
495
  recommendation: "Return a JSON-RPC error or set isError: true when tools/call receives an unrecognized tool name. Do not return an empty success response."
442
496
  },
497
+ {
498
+ id: "error-capability-gated",
499
+ name: "Rejects methods for undeclared capabilities",
500
+ category: "errors",
501
+ required: false,
502
+ specRef: "basic/lifecycle#capability-negotiation",
503
+ description: "Calls list methods (tools/list, resources/list, prompts/list) for capabilities the server did NOT declare, and verifies the server returns an error instead of success.",
504
+ recommendation: "Return a JSON-RPC error (e.g., -32601 Method not found) for methods associated with capabilities not declared in your initialize response."
505
+ },
506
+ {
507
+ id: "error-invalid-cursor",
508
+ name: "Handles invalid pagination cursor gracefully",
509
+ category: "errors",
510
+ required: false,
511
+ specRef: "basic",
512
+ description: "Sends a garbage pagination cursor to a list method and verifies the server handles it gracefully \u2014 either returning an error or ignoring the invalid cursor.",
513
+ recommendation: "Validate pagination cursors before use. Return a JSON-RPC error for unrecognized cursors, or treat invalid cursors as a request for the first page."
514
+ },
443
515
  // ── Schema Validation (6 tests) ──────────────────────────────────
444
516
  {
445
517
  id: "tools-schema",
@@ -456,8 +528,8 @@ var TEST_DEFINITIONS = [
456
528
  category: "schema",
457
529
  required: false,
458
530
  specRef: "server/tools#annotations",
459
- description: "Validates tool annotation fields if present: readOnlyHint, destructiveHint, idempotentHint, openWorldHint should be booleans; title should be a string.",
460
- recommendation: "If you include annotations on tools, ensure readOnlyHint, destructiveHint, idempotentHint, and openWorldHint are booleans. Title must be a string."
531
+ description: "Validates tool annotation fields if present: readOnlyHint, destructiveHint, idempotentHint, openWorldHint should be booleans.",
532
+ recommendation: "If you include annotations on tools, ensure readOnlyHint, destructiveHint, idempotentHint, and openWorldHint are booleans. Note: title belongs on the Tool object, not inside annotations."
461
533
  },
462
534
  {
463
535
  id: "tools-title-field",
@@ -494,22 +566,275 @@ var TEST_DEFINITIONS = [
494
566
  specRef: "server/resources#data-types",
495
567
  description: "Validates every resource has a valid URI (parseable as a URL) and a name field.",
496
568
  recommendation: "Ensure every resource has a valid, parseable URI and a name field. Add description and mimeType for better client integration."
569
+ },
570
+ // ── Security: Auth & Transport (9 tests) ─────────────────────────
571
+ {
572
+ id: "security-auth-required",
573
+ name: "Rejects unauthenticated requests",
574
+ category: "security",
575
+ required: false,
576
+ specRef: "basic/authorization",
577
+ description: "Sends a request without an Authorization header and verifies the server returns HTTP 401. Servers exposed over the network should require authentication.",
578
+ recommendation: "Implement authentication on your MCP endpoint. Return HTTP 401 Unauthorized for requests without valid credentials. Use OAuth 2.1 or Bearer tokens as recommended by the MCP spec."
579
+ },
580
+ {
581
+ id: "security-auth-malformed",
582
+ name: "Rejects malformed auth credentials",
583
+ category: "security",
584
+ required: false,
585
+ specRef: "basic/authorization",
586
+ description: "Sends a request with a malformed Authorization header (garbage value) and verifies the server returns HTTP 401 or 403. Servers must validate auth tokens, not just check for presence.",
587
+ recommendation: "Validate the format and signature of Authorization header values. Reject malformed or invalid tokens with HTTP 401. Do not treat any non-empty Authorization header as valid."
588
+ },
589
+ {
590
+ id: "security-tls-required",
591
+ name: "Enforces HTTPS/TLS",
592
+ category: "security",
593
+ required: false,
594
+ specRef: "basic/authorization",
595
+ description: "If the server URL uses HTTPS, attempts an HTTP (plaintext) connection and verifies it is rejected or redirected. Production MCP servers should not accept plaintext connections.",
596
+ recommendation: "Configure your server to reject HTTP connections or redirect to HTTPS. Use TLS 1.2 or higher. The MCP spec requires HTTPS for production deployments."
597
+ },
598
+ {
599
+ id: "security-session-entropy",
600
+ name: "Session IDs are high-entropy",
601
+ category: "security",
602
+ required: false,
603
+ specRef: "basic/transports#streamable-http",
604
+ description: "Analyzes the MCP-Session-Id returned by the server. Session IDs should be cryptographically random and not sequential or predictable.",
605
+ recommendation: "Generate session IDs using a cryptographically secure random source (e.g., crypto.randomUUID()). Session IDs should be at least 128 bits of entropy. Do not use sequential counters or timestamps."
606
+ },
607
+ {
608
+ id: "security-session-not-auth",
609
+ name: "Session ID does not bypass auth",
610
+ category: "security",
611
+ required: false,
612
+ specRef: "basic/transports#streamable-http",
613
+ description: "Verifies that presenting a valid MCP-Session-Id without an Authorization header is still rejected. Per spec, servers MUST NOT use sessions for authentication.",
614
+ recommendation: "Always validate the Authorization header independently of the MCP-Session-Id. Sessions are for request routing, not authentication. Reject requests that lack valid auth even if they have a valid session ID."
615
+ },
616
+ {
617
+ id: "security-oauth-metadata",
618
+ name: "Protected Resource Metadata endpoint exists",
619
+ category: "security",
620
+ required: false,
621
+ specRef: "basic/authorization",
622
+ description: "Checks for a Protected Resource Metadata (RFC 9728) endpoint at /.well-known/oauth-protected-resource. Per MCP 2025-11-25, the MCP server publishes PRM with a resource identifier and authorization_servers array. Falls back to legacy /.well-known/oauth-authorization-server with a warning.",
623
+ recommendation: "Publish a Protected Resource Metadata document at /.well-known/oauth-protected-resource on your server's origin. Include 'resource' (your server's URL) and 'authorization_servers' (array of OAuth AS URLs). See RFC 9728."
624
+ },
625
+ {
626
+ id: "security-token-in-uri",
627
+ name: "Rejects auth tokens in query string",
628
+ category: "security",
629
+ required: false,
630
+ specRef: "basic/authorization",
631
+ description: "Sends a request with the auth token in the URL query string instead of the Authorization header. The MCP spec forbids transmitting credentials in URIs.",
632
+ recommendation: "Never accept authentication tokens from URL query parameters. Tokens in URIs are logged by proxies, appear in browser history, and leak via the Referer header. Only accept tokens in the Authorization header."
633
+ },
634
+ {
635
+ id: "security-cors-headers",
636
+ name: "CORS headers are restrictive",
637
+ category: "security",
638
+ required: false,
639
+ specRef: "basic/transports#streamable-http",
640
+ description: "If the server returns CORS headers, verifies that Access-Control-Allow-Origin is not set to wildcard (*). Wildcard CORS on an authenticated API allows cross-origin credential theft.",
641
+ recommendation: 'Set Access-Control-Allow-Origin to specific trusted origins, not "*". If CORS is not needed (server-to-server only), do not send CORS headers at all.'
642
+ },
643
+ {
644
+ id: "security-origin-validation",
645
+ name: "Validates Origin header on requests",
646
+ category: "security",
647
+ required: false,
648
+ specRef: "basic/transports#streamable-http",
649
+ description: "Sends a request with a suspicious Origin header (https://evil-rebinding-attack.example.com) and verifies the server rejects it. Per spec, servers MUST validate the Origin header to prevent DNS rebinding attacks.",
650
+ recommendation: "Validate the Origin header on all incoming requests. Reject requests from untrusted origins with HTTP 403. Maintain an allowlist of permitted origins."
651
+ },
652
+ // ── Security: Input Validation (6 tests) ─────────────────────────
653
+ {
654
+ id: "security-command-injection",
655
+ name: "Resists command injection in tool params",
656
+ category: "security",
657
+ required: false,
658
+ specRef: "server/tools#calling-tools",
659
+ description: "Calls each tool with OS command injection payloads in string parameters (e.g., '; cat /etc/passwd', '$(whoami)'). Verifies the server does not execute injected commands.",
660
+ recommendation: "Never pass tool argument values directly to shell commands. Use parameterized APIs, execFile() instead of exec(), or allowlists. Sanitize all user-provided input before use in system calls."
661
+ },
662
+ {
663
+ id: "security-sql-injection",
664
+ name: "Resists SQL injection in tool params",
665
+ category: "security",
666
+ required: false,
667
+ specRef: "server/tools#calling-tools",
668
+ description: `Calls each tool with SQL injection payloads in string parameters (e.g., "' OR 1=1 --"). Verifies the server does not return database errors or unexpected data.`,
669
+ recommendation: "Use parameterized queries or prepared statements for all database operations. Never concatenate user input into SQL strings. Return generic error messages that do not reveal database structure."
670
+ },
671
+ {
672
+ id: "security-path-traversal",
673
+ name: "Resists path traversal in tool params",
674
+ category: "security",
675
+ required: false,
676
+ specRef: "server/tools#calling-tools",
677
+ description: "Calls each tool with path traversal payloads in string parameters (e.g., '../../etc/passwd', '..\\\\..\\\\windows\\\\system.ini'). Verifies the server does not expose files outside its intended scope.",
678
+ recommendation: "Validate and sanitize file paths. Use path.resolve() and verify the result is within the allowed directory. Reject paths containing '..' segments. Use a chroot or sandboxed filesystem for file operations."
679
+ },
680
+ {
681
+ id: "security-ssrf-internal",
682
+ name: "Resists SSRF to internal networks",
683
+ category: "security",
684
+ required: false,
685
+ specRef: "server/tools#calling-tools",
686
+ description: "For tools that accept URL parameters, submits internal IP addresses (169.254.169.254, 127.0.0.1, 10.0.0.0/8) and cloud metadata endpoints. Verifies the server blocks requests to internal networks.",
687
+ recommendation: "Validate and restrict URLs in tool parameters. Block requests to private IP ranges (10.x, 172.16-31.x, 192.168.x, 127.x, 169.254.x), link-local addresses, and cloud metadata endpoints. Use an allowlist of permitted domains."
688
+ },
689
+ {
690
+ id: "security-oversized-input",
691
+ name: "Handles oversized inputs gracefully",
692
+ category: "security",
693
+ required: false,
694
+ specRef: "server/tools#calling-tools",
695
+ description: "Sends a tools/call request with an extremely large argument value (1MB+ string). Verifies the server rejects it with an error instead of crashing or consuming excessive resources.",
696
+ recommendation: "Implement request body size limits. Return HTTP 413 or JSON-RPC error for oversized payloads. Set explicit maxBodyLength in your HTTP server configuration."
697
+ },
698
+ {
699
+ id: "security-extra-params",
700
+ name: "Rejects or ignores extra tool params",
701
+ category: "security",
702
+ required: false,
703
+ specRef: "server/tools#calling-tools",
704
+ description: "Calls a tool with unexpected additional parameters beyond what the schema defines. Verifies the server either rejects them (strict) or silently ignores them (permissive) without errors.",
705
+ recommendation: "Use JSON Schema validation with additionalProperties: false to reject unexpected parameters, or strip unknown properties before processing. Do not pass unvalidated properties to internal functions."
706
+ },
707
+ // ── Security: Tool Integrity (4 tests) ───────────────────────────
708
+ {
709
+ id: "security-tool-schema-defined",
710
+ name: "All tools define inputSchema",
711
+ category: "security",
712
+ required: false,
713
+ specRef: "server/tools#data-types",
714
+ description: "Verifies all tools have an inputSchema with type 'object'. Tools without schemas cannot have their inputs validated, creating an injection risk.",
715
+ recommendation: "Define a complete JSON Schema (inputSchema with type: 'object') for every tool. Specify all expected properties, their types, and constraints. This enables input validation and prevents parameter injection."
716
+ },
717
+ {
718
+ id: "security-tool-rug-pull",
719
+ name: "Tool definitions are stable across calls",
720
+ category: "security",
721
+ required: false,
722
+ specRef: "server/tools#listing-tools",
723
+ description: "Calls tools/list twice and compares the results. Tool definitions should not change between calls within the same session, which could indicate a rug-pull attack.",
724
+ recommendation: "Ensure tools/list returns consistent results within a session. If tools change dynamically, send a tools/list_changed notification. Never silently alter tool definitions \u2014 this is a known MCP attack vector (tool poisoning)."
725
+ },
726
+ {
727
+ id: "security-tool-description-poisoning",
728
+ name: "Tool descriptions free of injection patterns",
729
+ category: "security",
730
+ required: false,
731
+ specRef: "server/tools#data-types",
732
+ description: "Scans all tool names, descriptions, and parameter descriptions for prompt injection patterns: 'ignore previous', 'override', 'system prompt', hidden Unicode characters, and Base64-encoded strings.",
733
+ recommendation: "Review all tool descriptions for prompt injection patterns. Remove any text that attempts to override LLM instructions, references system prompts, or contains hidden characters. Tool descriptions are rendered to LLMs and can be used for prompt injection."
734
+ },
735
+ {
736
+ id: "security-tool-cross-reference",
737
+ name: "Tools do not reference other tools by name",
738
+ category: "security",
739
+ required: false,
740
+ specRef: "server/tools#data-types",
741
+ description: "Checks that tool descriptions do not reference other tool names. Cross-references between tools can be used to manipulate LLM tool selection and create implicit execution chains.",
742
+ recommendation: "Avoid referencing other tool names in tool descriptions. Each tool should be self-contained. If tools have dependencies, document them in server instructions, not in individual tool descriptions."
743
+ },
744
+ // ── Security: Information Disclosure (3 tests) ───────────────────
745
+ {
746
+ id: "security-error-no-stacktrace",
747
+ name: "Error responses do not leak stack traces",
748
+ category: "security",
749
+ required: false,
750
+ specRef: "basic",
751
+ description: "Triggers various error conditions and inspects responses for stack traces, file paths, and internal implementation details. Error responses should not reveal server internals.",
752
+ recommendation: "Sanitize error responses before returning them to clients. Remove stack traces, file paths, database connection strings, and internal IP addresses. Use generic error messages for unexpected failures."
753
+ },
754
+ {
755
+ id: "security-error-no-internal-ip",
756
+ name: "Error responses do not leak internal IPs",
757
+ category: "security",
758
+ required: false,
759
+ specRef: "basic",
760
+ description: "Inspects error response bodies for private IP addresses (10.x, 172.16-31.x, 192.168.x, 127.x) that would reveal internal network topology.",
761
+ recommendation: "Strip internal IP addresses from error responses. Configure your reverse proxy to not forward X-Real-IP or internal addressing. Use a centralized error handler that sanitizes responses."
762
+ },
763
+ {
764
+ id: "security-rate-limiting",
765
+ name: "Rate limiting is enforced",
766
+ category: "security",
767
+ required: false,
768
+ specRef: "basic/transports#streamable-http",
769
+ description: "Sends a burst of rapid requests and checks if the server eventually returns HTTP 429 Too Many Requests. Production servers should implement rate limiting to prevent abuse.",
770
+ recommendation: "Implement rate limiting on your MCP endpoint. Return HTTP 429 with a Retry-After header when limits are exceeded. Consider per-IP, per-token, and per-session rate limits."
497
771
  }
498
772
  ];
499
773
 
500
774
  // src/runner.ts
775
+ var TEST_DEFINITIONS_MAP = new Map(TEST_DEFINITIONS.map((t) => [t.id, t]));
501
776
  var _require = createRequire(import.meta.url);
502
777
  var { version: TOOL_VERSION } = _require("../package.json");
503
778
  var SPEC_VERSION = "2025-11-25";
504
779
  var SPEC_BASE = `https://modelcontextprotocol.io/specification/${SPEC_VERSION}`;
505
780
  var VALID_CONTENT_TYPES = ["text", "image", "audio", "resource", "resource_link"];
781
+ var INJECTION_PAYLOADS = {
782
+ command: ["; cat /etc/passwd", "$(whoami)", "| ls -la", "`id`", "&& echo pwned"],
783
+ sql: ["' OR 1=1 --", "'; DROP TABLE users; --", "1 UNION SELECT * FROM information_schema.tables--"],
784
+ pathTraversal: ["../../etc/passwd", "..\\..\\windows\\system.ini", "%2e%2e%2f%2e%2e%2fetc%2fpasswd"],
785
+ ssrf: ["http://169.254.169.254/latest/meta-data/", "http://127.0.0.1:22", "http://[::1]/", "http://10.0.0.1/"]
786
+ };
787
+ var STACK_TRACE_PATTERNS = [
788
+ /at\s+\S+\s+\(.*:\d+:\d+\)/i,
789
+ // Node.js: "at Function (file.js:10:5)"
790
+ /Traceback\s+\(most recent/i,
791
+ // Python
792
+ /\.py",\s+line\s+\d+/i,
793
+ // Python file reference
794
+ /\.java:\d+\)/i,
795
+ // Java
796
+ /\.go:\d+/i,
797
+ // Go
798
+ /from\s+\S+\.rb:\d+/i,
799
+ // Ruby
800
+ /\.cs:line\s+\d+/i,
801
+ // C#/.NET
802
+ /#\d+\s+\/.*\.php\(\d+\)/i,
803
+ // PHP
804
+ /panicked\s+at\s+'/i,
805
+ // Rust
806
+ /ENOENT|EACCES|EPERM/,
807
+ // Node.js system errors
808
+ /node_modules\//,
809
+ // Node.js module paths
810
+ /\/usr\/local\/|\/home\//,
811
+ // Unix paths
812
+ /[A-Z]:\\.*\\/,
813
+ // Windows paths
814
+ /password|passwd|secret|credential/i,
815
+ // Sensitive terms
816
+ /jdbc:|mysql:|postgres:|mongodb:/i
817
+ // DB connection strings
818
+ ];
819
+ var INTERNAL_IP_PATTERNS = [
820
+ /\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,
821
+ /\b172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/,
822
+ /\b192\.168\.\d{1,3}\.\d{1,3}\b/,
823
+ /\b127\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,
824
+ /\b::1\b/,
825
+ // IPv6 loopback
826
+ /\bfe80:/i,
827
+ // IPv6 link-local
828
+ /\bf[cd][0-9a-f]{2}:/i
829
+ // IPv6 unique local (fc00::/fd00::)
830
+ ];
506
831
  function createIdCounter(start = 0) {
507
832
  let id = start;
508
833
  return () => ++id;
509
834
  }
510
835
  function parseSSEResponse(text) {
511
836
  const lines = text.split("\n");
512
- let lastJsonRpcResponse = null;
837
+ let firstJsonRpcResponse = null;
513
838
  let currentData = [];
514
839
  function flushEvent() {
515
840
  if (currentData.length === 0) return;
@@ -518,8 +843,8 @@ function parseSSEResponse(text) {
518
843
  if (!data.trim()) return;
519
844
  try {
520
845
  const parsed = JSON.parse(data);
521
- if (parsed.jsonrpc === "2.0" && parsed.id !== void 0) {
522
- lastJsonRpcResponse = parsed;
846
+ if (!firstJsonRpcResponse && parsed.jsonrpc === "2.0" && parsed.id !== void 0) {
847
+ firstJsonRpcResponse = parsed;
523
848
  }
524
849
  } catch {
525
850
  }
@@ -533,7 +858,7 @@ function parseSSEResponse(text) {
533
858
  }
534
859
  }
535
860
  flushEvent();
536
- return lastJsonRpcResponse;
861
+ return firstJsonRpcResponse;
537
862
  }
538
863
  async function mcpRequest(backendUrl, method, params, nextId, extraHeaders, timeout) {
539
864
  const id = nextId();
@@ -743,6 +1068,32 @@ async function runComplianceSuite(url, options = {}) {
743
1068
  return { passed: valid, details: `Content-Type: ${ct}` };
744
1069
  }
745
1070
  );
1071
+ await test(
1072
+ "transport-content-type-reject",
1073
+ "Rejects non-JSON request Content-Type",
1074
+ "transport",
1075
+ false,
1076
+ "basic/transports#streamable-http",
1077
+ async () => {
1078
+ const res = await request(backendUrl, {
1079
+ method: "POST",
1080
+ headers: { "Content-Type": "text/plain", Accept: "application/json, text/event-stream", ...userHeaders },
1081
+ body: JSON.stringify({ jsonrpc: "2.0", id: 99905, method: "ping" }),
1082
+ signal: AbortSignal.timeout(timeout)
1083
+ });
1084
+ await res.body.text();
1085
+ if (res.statusCode >= 400 && res.statusCode < 500) {
1086
+ return { passed: true, details: `HTTP ${res.statusCode} (incorrect Content-Type rejected)` };
1087
+ }
1088
+ if (res.statusCode >= 200 && res.statusCode < 300) {
1089
+ return {
1090
+ passed: false,
1091
+ details: `HTTP ${res.statusCode} \u2014 server accepted text/plain Content-Type (should require application/json)`
1092
+ };
1093
+ }
1094
+ return { passed: false, details: `HTTP ${res.statusCode}` };
1095
+ }
1096
+ );
746
1097
  await test(
747
1098
  "transport-get",
748
1099
  "GET returns SSE stream or 405",
@@ -757,7 +1108,8 @@ async function runComplianceSuite(url, options = {}) {
757
1108
  signal: AbortSignal.timeout(timeout)
758
1109
  });
759
1110
  const body = await res.body.text();
760
- const ct = (res.headers["content-type"] || "").toLowerCase();
1111
+ const rawCt = res.headers["content-type"];
1112
+ const ct = (Array.isArray(rawCt) ? rawCt[0] : rawCt || "").toLowerCase();
761
1113
  if (res.statusCode === 405) {
762
1114
  return { passed: true, details: "HTTP 405 Method Not Allowed (acceptable)" };
763
1115
  }
@@ -865,6 +1217,50 @@ async function runComplianceSuite(url, options = {}) {
865
1217
  return { passed: valid, details: `Version: ${version}` };
866
1218
  }
867
1219
  );
1220
+ await test(
1221
+ "lifecycle-version-negotiate",
1222
+ "Handles unknown protocol version",
1223
+ "lifecycle",
1224
+ false,
1225
+ "basic/lifecycle#version-negotiation",
1226
+ async () => {
1227
+ try {
1228
+ const futureRes = await mcpRequest(
1229
+ backendUrl,
1230
+ "initialize",
1231
+ {
1232
+ protocolVersion: "2099-01-01",
1233
+ capabilities: {},
1234
+ clientInfo: { name: "mcp-compliance", version: TOOL_VERSION }
1235
+ },
1236
+ createIdCounter(99960),
1237
+ userHeaders,
1238
+ timeout
1239
+ );
1240
+ const result = futureRes.body?.result;
1241
+ const error = futureRes.body?.error;
1242
+ if (error) {
1243
+ return {
1244
+ passed: true,
1245
+ details: `Server rejected unknown version with error: ${error.code} \u2014 ${error.message}`
1246
+ };
1247
+ }
1248
+ if (result?.protocolVersion) {
1249
+ const offered = result.protocolVersion;
1250
+ if (offered === "2099-01-01") {
1251
+ return {
1252
+ passed: false,
1253
+ details: 'Server accepted impossible future version "2099-01-01" \u2014 should offer a version it actually supports'
1254
+ };
1255
+ }
1256
+ return { passed: true, details: `Server negotiated down to ${offered} (correct)` };
1257
+ }
1258
+ return { passed: false, details: "No protocolVersion or error in response" };
1259
+ } catch {
1260
+ return { passed: true, details: "Connection rejected for unknown version (acceptable)" };
1261
+ }
1262
+ }
1263
+ );
868
1264
  await test(
869
1265
  "lifecycle-server-info",
870
1266
  "Includes serverInfo",
@@ -936,6 +1332,73 @@ async function runComplianceSuite(url, options = {}) {
936
1332
  details: match ? `Request id=${res.requestId}, response id=${body.id} (match)` : `Request id=${res.requestId}, response id=${body.id} (MISMATCH)`
937
1333
  };
938
1334
  });
1335
+ await test("lifecycle-string-id", "Supports string request IDs", "lifecycle", false, "basic", async () => {
1336
+ const stringId = "compliance-test-string-id";
1337
+ const body = JSON.stringify({ jsonrpc: "2.0", id: stringId, method: "ping", params: {} });
1338
+ const res = await request(backendUrl, {
1339
+ method: "POST",
1340
+ headers: {
1341
+ "Content-Type": "application/json",
1342
+ Accept: "application/json, text/event-stream",
1343
+ ...buildHeaders()
1344
+ },
1345
+ body,
1346
+ signal: AbortSignal.timeout(timeout)
1347
+ });
1348
+ const text = await res.body.text();
1349
+ const rawCtStr = res.headers["content-type"];
1350
+ const ct = (Array.isArray(rawCtStr) ? rawCtStr[0] : rawCtStr || "").toLowerCase();
1351
+ let parsed;
1352
+ if (ct.includes("text/event-stream")) {
1353
+ parsed = parseSSEResponse(text);
1354
+ }
1355
+ if (!parsed) {
1356
+ try {
1357
+ parsed = JSON.parse(text);
1358
+ } catch {
1359
+ }
1360
+ }
1361
+ if (!parsed) return { passed: false, details: "Could not parse response" };
1362
+ if (parsed.id === stringId) {
1363
+ return { passed: true, details: `String id="${stringId}" echoed back correctly` };
1364
+ }
1365
+ if (parsed.id === void 0) {
1366
+ return { passed: false, details: "No id in response" };
1367
+ }
1368
+ return {
1369
+ passed: false,
1370
+ details: `String id="${stringId}" sent, got back id=${JSON.stringify(parsed.id)} (type: ${typeof parsed.id})`
1371
+ };
1372
+ });
1373
+ await test(
1374
+ "lifecycle-reinit-reject",
1375
+ "Rejects second initialize request",
1376
+ "lifecycle",
1377
+ false,
1378
+ "basic/lifecycle#initialization",
1379
+ async () => {
1380
+ try {
1381
+ const res = await rpc("initialize", {
1382
+ protocolVersion: SPEC_VERSION,
1383
+ capabilities: {},
1384
+ clientInfo: { name: "mcp-compliance", version: TOOL_VERSION }
1385
+ });
1386
+ const error = res.body?.error;
1387
+ if (error) {
1388
+ return { passed: true, details: `Re-initialization rejected with error: ${error.code} \u2014 ${error.message}` };
1389
+ }
1390
+ if (res.statusCode >= 400) {
1391
+ return { passed: true, details: `HTTP ${res.statusCode} (re-initialization rejected)` };
1392
+ }
1393
+ return {
1394
+ passed: false,
1395
+ details: `Server accepted second initialize (HTTP ${res.statusCode}) \u2014 should reject duplicate initialization`
1396
+ };
1397
+ } catch {
1398
+ return { passed: true, details: "Connection rejected (acceptable)" };
1399
+ }
1400
+ }
1401
+ );
939
1402
  const hasLogging = !!serverInfo.capabilities.logging;
940
1403
  await test(
941
1404
  "lifecycle-logging",
@@ -1010,7 +1473,7 @@ async function runComplianceSuite(url, options = {}) {
1010
1473
  );
1011
1474
  await test(
1012
1475
  "lifecycle-progress",
1013
- "Accepts progress notifications",
1476
+ "Handles progress notifications gracefully",
1014
1477
  "lifecycle",
1015
1478
  false,
1016
1479
  "basic/utilities#progress",
@@ -1023,9 +1486,12 @@ async function runComplianceSuite(url, options = {}) {
1023
1486
  timeout
1024
1487
  );
1025
1488
  if (res.statusCode >= 200 && res.statusCode < 300) {
1026
- return { passed: true, details: `HTTP ${res.statusCode} (progress notification accepted)` };
1489
+ return { passed: true, details: `HTTP ${res.statusCode} (notification handled gracefully)` };
1027
1490
  }
1028
- return { passed: false, details: `HTTP ${res.statusCode} \u2014 server should accept progress notifications` };
1491
+ return {
1492
+ passed: false,
1493
+ details: `HTTP ${res.statusCode} \u2014 server should accept unknown notifications without error`
1494
+ };
1029
1495
  }
1030
1496
  );
1031
1497
  await test(
@@ -1067,7 +1533,11 @@ async function runComplianceSuite(url, options = {}) {
1067
1533
  return { passed: true, details: "HTTP 202 Accepted (correct)" };
1068
1534
  }
1069
1535
  if (res.statusCode >= 200 && res.statusCode < 300) {
1070
- return { passed: true, details: `HTTP ${res.statusCode} (accepted, but 202 is preferred)` };
1536
+ warnings.push(`Notification returned HTTP ${res.statusCode} instead of spec-required 202 Accepted`);
1537
+ return {
1538
+ passed: false,
1539
+ details: `HTTP ${res.statusCode} \u2014 spec requires 202 Accepted for notifications (MUST)`
1540
+ };
1071
1541
  }
1072
1542
  return { passed: false, details: `HTTP ${res.statusCode} \u2014 expected 202 Accepted for notifications` };
1073
1543
  }
@@ -1098,6 +1568,34 @@ async function runComplianceSuite(url, options = {}) {
1098
1568
  return { passed: false, details: `HTTP ${res.statusCode}` };
1099
1569
  }
1100
1570
  );
1571
+ await test(
1572
+ "transport-session-invalid",
1573
+ "Returns 404 for unknown session ID",
1574
+ "transport",
1575
+ false,
1576
+ "basic/transports#streamable-http",
1577
+ async () => {
1578
+ if (!sessionId) {
1579
+ return { passed: true, details: "Server did not issue session ID (test not applicable)" };
1580
+ }
1581
+ const fakeHeaders = {
1582
+ ...userHeaders,
1583
+ "mcp-session-id": "invalid-nonexistent-session-id"
1584
+ };
1585
+ if (negotiatedProtocolVersion) fakeHeaders["mcp-protocol-version"] = negotiatedProtocolVersion;
1586
+ const res = await mcpRequest(backendUrl, "ping", void 0, createIdCounter(99915), fakeHeaders, timeout);
1587
+ if (res.statusCode === 404) {
1588
+ return { passed: true, details: "HTTP 404 for unknown session ID (correct per spec)" };
1589
+ }
1590
+ if (res.statusCode === 400) {
1591
+ return {
1592
+ passed: false,
1593
+ details: "HTTP 400 \u2014 spec requires 404 (Not Found) for unrecognized session IDs, not 400"
1594
+ };
1595
+ }
1596
+ return { passed: false, details: `HTTP ${res.statusCode} \u2014 spec requires 404 for unrecognized MCP-Session-Id` };
1597
+ }
1598
+ );
1101
1599
  await test(
1102
1600
  "transport-get-stream",
1103
1601
  "GET with session returns SSE or 405",
@@ -1114,7 +1612,8 @@ async function runComplianceSuite(url, options = {}) {
1114
1612
  signal: AbortSignal.timeout(Math.min(timeout, 3e3))
1115
1613
  });
1116
1614
  const body = await res.body.text();
1117
- const ct = (res.headers["content-type"] || "").toLowerCase();
1615
+ const rawCt2 = res.headers["content-type"];
1616
+ const ct = (Array.isArray(rawCt2) ? rawCt2[0] : rawCt2 || "").toLowerCase();
1118
1617
  if (res.statusCode === 405) {
1119
1618
  return { passed: true, details: "HTTP 405 (server does not support server-initiated messages)" };
1120
1619
  }
@@ -1153,7 +1652,8 @@ async function runComplianceSuite(url, options = {}) {
1153
1652
  signal: AbortSignal.timeout(timeout)
1154
1653
  }).then(async (res) => {
1155
1654
  const text = await res.body.text();
1156
- const ct = (res.headers["content-type"] || "").toLowerCase();
1655
+ const rawCtConcurrent = res.headers["content-type"];
1656
+ const ct = (Array.isArray(rawCtConcurrent) ? rawCtConcurrent[0] : rawCtConcurrent || "").toLowerCase();
1157
1657
  let body;
1158
1658
  if (ct.includes("text/event-stream")) {
1159
1659
  body = parseSSEResponse(text);
@@ -1180,6 +1680,42 @@ async function runComplianceSuite(url, options = {}) {
1180
1680
  return { passed: true, details: `${results.length} concurrent requests handled correctly` };
1181
1681
  }
1182
1682
  );
1683
+ await test(
1684
+ "transport-sse-event-field",
1685
+ "SSE responses include event: message",
1686
+ "transport",
1687
+ false,
1688
+ "basic/transports#streamable-http",
1689
+ async () => {
1690
+ const res = await request(backendUrl, {
1691
+ method: "POST",
1692
+ headers: {
1693
+ "Content-Type": "application/json",
1694
+ Accept: "text/event-stream",
1695
+ ...buildHeaders()
1696
+ },
1697
+ body: JSON.stringify({ jsonrpc: "2.0", id: createIdCounter(99940)(), method: "ping" }),
1698
+ signal: AbortSignal.timeout(timeout)
1699
+ });
1700
+ const text = await res.body.text();
1701
+ const rawCtSse = res.headers["content-type"];
1702
+ const ct = (Array.isArray(rawCtSse) ? rawCtSse[0] : rawCtSse || "").toLowerCase();
1703
+ if (!ct.includes("text/event-stream")) {
1704
+ return { passed: true, details: "Server responded with JSON (not SSE) \u2014 event field check not applicable" };
1705
+ }
1706
+ const hasEventMessage = /^event:\s*message\s*$/m.test(text);
1707
+ if (hasEventMessage) {
1708
+ return { passed: true, details: "SSE response includes required event: message field" };
1709
+ }
1710
+ if (text.includes("data:")) {
1711
+ return {
1712
+ passed: false,
1713
+ details: "SSE response has data: fields but missing required event: message field (spec: MUST include event: message)"
1714
+ };
1715
+ }
1716
+ return { passed: true, details: "SSE response empty or no data fields \u2014 check not applicable" };
1717
+ }
1718
+ );
1183
1719
  const hasTools = !!serverInfo.capabilities.tools;
1184
1720
  let cachedToolsList = null;
1185
1721
  await test(
@@ -1261,9 +1797,6 @@ async function runComplianceSuite(url, options = {}) {
1261
1797
  issues.push(`${tool.name}: annotations.${field} should be boolean, got ${typeof ann[field]}`);
1262
1798
  }
1263
1799
  }
1264
- if (ann.title !== void 0 && typeof ann.title !== "string") {
1265
- issues.push(`${tool.name}: annotations.title should be string`);
1266
- }
1267
1800
  }
1268
1801
  if (issues.length > 0) return { passed: false, details: issues.join("; ") };
1269
1802
  return {
@@ -1811,6 +2344,822 @@ async function runComplianceSuite(url, options = {}) {
1811
2344
  }
1812
2345
  return { passed: false, details: `HTTP ${res.statusCode} \u2014 expected error code -32600` };
1813
2346
  });
2347
+ const undeclaredMethods = [
2348
+ { method: "tools/list", capability: "tools", declared: hasTools },
2349
+ { method: "resources/list", capability: "resources", declared: hasResources },
2350
+ { method: "prompts/list", capability: "prompts", declared: hasPrompts }
2351
+ ];
2352
+ const undeclared = undeclaredMethods.filter((m) => !m.declared);
2353
+ await test(
2354
+ "error-capability-gated",
2355
+ "Rejects methods for undeclared capabilities",
2356
+ "errors",
2357
+ false,
2358
+ "basic/lifecycle#capability-negotiation",
2359
+ async () => {
2360
+ if (undeclared.length === 0) {
2361
+ return {
2362
+ passed: true,
2363
+ details: "Server declares all capabilities (tools, resources, prompts) \u2014 no undeclared methods to test"
2364
+ };
2365
+ }
2366
+ const issues = [];
2367
+ for (const { method, capability } of undeclared) {
2368
+ const res = await rpc(method);
2369
+ const error = res.body?.error;
2370
+ if (!error && res.body?.result) {
2371
+ issues.push(`${method} returned success despite missing ${capability} capability`);
2372
+ }
2373
+ }
2374
+ if (issues.length > 0) return { passed: false, details: issues.join("; ") };
2375
+ return {
2376
+ passed: true,
2377
+ details: `Tested ${undeclared.length} undeclared method(s): ${undeclared.map((m) => m.method).join(", ")} \u2014 all returned errors`
2378
+ };
2379
+ }
2380
+ );
2381
+ const listMethodForCursor = hasTools ? "tools/list" : hasResources ? "resources/list" : hasPrompts ? "prompts/list" : null;
2382
+ await test(
2383
+ "error-invalid-cursor",
2384
+ "Handles invalid pagination cursor gracefully",
2385
+ "errors",
2386
+ false,
2387
+ "basic",
2388
+ async () => {
2389
+ if (!listMethodForCursor) {
2390
+ return { passed: true, details: "No list methods available to test (skipped)" };
2391
+ }
2392
+ const res = await rpc(listMethodForCursor, { cursor: "!!!invalid-garbage-cursor-$$$" });
2393
+ const error = res.body?.error;
2394
+ if (error) {
2395
+ return { passed: true, details: `Invalid cursor rejected with error: ${error.code} \u2014 ${error.message}` };
2396
+ }
2397
+ const result = res.body?.result;
2398
+ if (result) {
2399
+ return { passed: true, details: "Server returned results (likely ignored invalid cursor)" };
2400
+ }
2401
+ return { passed: false, details: "No error or result for invalid cursor" };
2402
+ }
2403
+ );
2404
+ const hasAuth = !!userHeaders.Authorization || !!userHeaders.authorization;
2405
+ await test(
2406
+ "security-auth-required",
2407
+ "Rejects unauthenticated requests",
2408
+ "security",
2409
+ false,
2410
+ "basic/authorization",
2411
+ async () => {
2412
+ if (!hasAuth) {
2413
+ return {
2414
+ passed: false,
2415
+ details: "Server does not require auth (no --auth provided and server accepted unauthenticated requests)"
2416
+ };
2417
+ }
2418
+ const noAuthHeaders = {};
2419
+ if (sessionId) noAuthHeaders["mcp-session-id"] = sessionId;
2420
+ try {
2421
+ const res = await mcpRequest(backendUrl, "ping", void 0, nextId, noAuthHeaders, timeout);
2422
+ if (res.statusCode === 401 || res.statusCode === 403) {
2423
+ return { passed: true, details: `HTTP ${res.statusCode} (unauthenticated request rejected)` };
2424
+ }
2425
+ return { passed: false, details: `HTTP ${res.statusCode} \u2014 server accepted unauthenticated request` };
2426
+ } catch (err) {
2427
+ return { passed: true, details: "Connection rejected (acceptable)" };
2428
+ }
2429
+ }
2430
+ );
2431
+ await test(
2432
+ "security-auth-malformed",
2433
+ "Rejects malformed auth credentials",
2434
+ "security",
2435
+ false,
2436
+ "basic/authorization",
2437
+ async () => {
2438
+ if (!hasAuth) {
2439
+ return { passed: false, details: "Skipped: server does not require auth" };
2440
+ }
2441
+ const malformedHeaders = {
2442
+ Authorization: "Bearer INVALID_GARBAGE_TOKEN_!@#$%^&*()"
2443
+ };
2444
+ if (sessionId) malformedHeaders["mcp-session-id"] = sessionId;
2445
+ try {
2446
+ const res = await mcpRequest(backendUrl, "ping", void 0, nextId, malformedHeaders, timeout);
2447
+ if (res.statusCode === 401 || res.statusCode === 403) {
2448
+ return { passed: true, details: `HTTP ${res.statusCode} (malformed auth rejected)` };
2449
+ }
2450
+ return { passed: false, details: `HTTP ${res.statusCode} \u2014 server accepted malformed auth token` };
2451
+ } catch (err) {
2452
+ return { passed: true, details: "Connection rejected (acceptable)" };
2453
+ }
2454
+ }
2455
+ );
2456
+ await test("security-tls-required", "Enforces HTTPS/TLS", "security", false, "basic/authorization", async () => {
2457
+ const parsedUrl = new URL(url);
2458
+ if (parsedUrl.protocol !== "https:") {
2459
+ return { passed: false, details: `Server URL uses ${parsedUrl.protocol} \u2014 production servers should use HTTPS` };
2460
+ }
2461
+ const httpUrl = url.replace(/^https:/, "http:");
2462
+ try {
2463
+ const res = await request(httpUrl, {
2464
+ method: "POST",
2465
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
2466
+ body: JSON.stringify({ jsonrpc: "2.0", id: 99950, method: "ping" }),
2467
+ signal: AbortSignal.timeout(Math.min(timeout, 5e3))
2468
+ });
2469
+ await res.body.text();
2470
+ if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 308) {
2471
+ return { passed: true, details: `HTTP ${res.statusCode} redirect to HTTPS (good)` };
2472
+ }
2473
+ if (res.statusCode >= 400) {
2474
+ return { passed: true, details: `HTTP ${res.statusCode} (plaintext rejected)` };
2475
+ }
2476
+ return { passed: false, details: `HTTP ${res.statusCode} \u2014 server accepts plaintext HTTP connections` };
2477
+ } catch {
2478
+ return { passed: true, details: "HTTP connection refused (HTTPS enforced)" };
2479
+ }
2480
+ });
2481
+ await test(
2482
+ "security-session-entropy",
2483
+ "Session IDs are high-entropy",
2484
+ "security",
2485
+ false,
2486
+ "basic/transports#streamable-http",
2487
+ async () => {
2488
+ if (!sessionId) {
2489
+ return { passed: true, details: "Server does not issue session IDs (skipped)" };
2490
+ }
2491
+ if (sessionId.length < 16) {
2492
+ return {
2493
+ passed: false,
2494
+ details: `Session ID too short (${sessionId.length} chars): "${sessionId}" \u2014 should be \u226516 chars`
2495
+ };
2496
+ }
2497
+ if (/^\d+$/.test(sessionId)) {
2498
+ return {
2499
+ passed: false,
2500
+ details: `Session ID is purely numeric: "${sessionId}" \u2014 likely sequential, not random`
2501
+ };
2502
+ }
2503
+ const uniqueChars = new Set(sessionId.toLowerCase()).size;
2504
+ if (uniqueChars < 8) {
2505
+ return {
2506
+ passed: false,
2507
+ details: `Session ID has low character diversity (${uniqueChars} unique chars): "${sessionId}"`
2508
+ };
2509
+ }
2510
+ return {
2511
+ passed: true,
2512
+ details: `Session ID has good entropy (${sessionId.length} chars, ${uniqueChars} unique): "${sessionId.substring(0, 16)}..."`
2513
+ };
2514
+ }
2515
+ );
2516
+ await test(
2517
+ "security-session-not-auth",
2518
+ "Session ID does not bypass auth",
2519
+ "security",
2520
+ false,
2521
+ "basic/transports#streamable-http",
2522
+ async () => {
2523
+ if (!hasAuth) {
2524
+ return { passed: true, details: "Skipped: server does not require auth" };
2525
+ }
2526
+ if (!sessionId) {
2527
+ return { passed: true, details: "Skipped: server does not issue session IDs" };
2528
+ }
2529
+ const sessionOnlyHeaders = {
2530
+ "mcp-session-id": sessionId
2531
+ };
2532
+ try {
2533
+ const res = await mcpRequest(backendUrl, "ping", void 0, nextId, sessionOnlyHeaders, timeout);
2534
+ if (res.statusCode === 401 || res.statusCode === 403) {
2535
+ return { passed: true, details: `HTTP ${res.statusCode} (session ID alone not sufficient for auth)` };
2536
+ }
2537
+ return {
2538
+ passed: false,
2539
+ details: `HTTP ${res.statusCode} \u2014 server accepted session ID without auth (spec: MUST NOT use sessions for authentication)`
2540
+ };
2541
+ } catch {
2542
+ return { passed: true, details: "Connection rejected (acceptable)" };
2543
+ }
2544
+ }
2545
+ );
2546
+ await test(
2547
+ "security-oauth-metadata",
2548
+ "Protected Resource Metadata endpoint exists",
2549
+ "security",
2550
+ false,
2551
+ "basic/authorization",
2552
+ async () => {
2553
+ if (!hasAuth) {
2554
+ return { passed: true, details: "Skipped: server does not require auth" };
2555
+ }
2556
+ const parsedUrl = new URL(url);
2557
+ const prmUrl = `${parsedUrl.protocol}//${parsedUrl.host}/.well-known/oauth-protected-resource`;
2558
+ try {
2559
+ const res = await request(prmUrl, {
2560
+ method: "GET",
2561
+ headers: { Accept: "application/json" },
2562
+ signal: AbortSignal.timeout(Math.min(timeout, 5e3))
2563
+ });
2564
+ const text = await res.body.text();
2565
+ if (res.statusCode === 200) {
2566
+ try {
2567
+ const meta = JSON.parse(text);
2568
+ if (!meta.resource) {
2569
+ return { passed: false, details: "PRM response missing required 'resource' field" };
2570
+ }
2571
+ if (!Array.isArray(meta.authorization_servers) || meta.authorization_servers.length === 0) {
2572
+ return { passed: false, details: "PRM response missing 'authorization_servers' array" };
2573
+ }
2574
+ return {
2575
+ passed: true,
2576
+ details: `Protected Resource Metadata found: resource=${meta.resource}, ${meta.authorization_servers.length} auth server(s)`
2577
+ };
2578
+ } catch {
2579
+ return { passed: false, details: "PRM endpoint returned non-JSON response" };
2580
+ }
2581
+ }
2582
+ const legacyUrl = `${parsedUrl.protocol}//${parsedUrl.host}/.well-known/oauth-authorization-server`;
2583
+ try {
2584
+ const legacyRes = await request(legacyUrl, {
2585
+ method: "GET",
2586
+ headers: { Accept: "application/json" },
2587
+ signal: AbortSignal.timeout(Math.min(timeout, 5e3))
2588
+ });
2589
+ const legacyText = await legacyRes.body.text();
2590
+ if (legacyRes.statusCode === 200) {
2591
+ try {
2592
+ const legacyMeta = JSON.parse(legacyText);
2593
+ if (legacyMeta.issuer && legacyMeta.token_endpoint) {
2594
+ warnings.push(
2595
+ "Server uses legacy /.well-known/oauth-authorization-server instead of /.well-known/oauth-protected-resource (RFC 9728). Update to PRM for 2025-11-25 compliance."
2596
+ );
2597
+ return {
2598
+ passed: true,
2599
+ details: `Legacy OAuth AS metadata found: issuer=${legacyMeta.issuer} (should migrate to PRM)`
2600
+ };
2601
+ }
2602
+ } catch {
2603
+ }
2604
+ }
2605
+ } catch {
2606
+ }
2607
+ return {
2608
+ passed: false,
2609
+ details: `PRM endpoint returned HTTP ${res.statusCode} and no legacy OAuth metadata found`
2610
+ };
2611
+ } catch {
2612
+ return { passed: false, details: "PRM endpoint unreachable" };
2613
+ }
2614
+ }
2615
+ );
2616
+ await test(
2617
+ "security-token-in-uri",
2618
+ "Rejects auth tokens in query string",
2619
+ "security",
2620
+ false,
2621
+ "basic/authorization",
2622
+ async () => {
2623
+ if (!hasAuth) {
2624
+ return { passed: true, details: "Skipped: server does not require auth" };
2625
+ }
2626
+ const authValue = userHeaders.Authorization || userHeaders.authorization || "";
2627
+ const token = authValue.replace(/^Bearer\s+/i, "");
2628
+ if (!token) {
2629
+ return { passed: true, details: "Skipped: could not extract token from auth header" };
2630
+ }
2631
+ const uriWithToken = `${url}${url.includes("?") ? "&" : "?"}access_token=${encodeURIComponent(token)}`;
2632
+ try {
2633
+ const noAuthHeaders = {};
2634
+ if (sessionId) noAuthHeaders["mcp-session-id"] = sessionId;
2635
+ const res = await mcpRequest(uriWithToken, "ping", void 0, nextId, noAuthHeaders, timeout);
2636
+ if (res.statusCode === 401 || res.statusCode === 403) {
2637
+ return { passed: true, details: `HTTP ${res.statusCode} (token in query string rejected)` };
2638
+ }
2639
+ if (res.statusCode >= 200 && res.statusCode < 300) {
2640
+ return {
2641
+ passed: false,
2642
+ details: "Server accepted auth token in query string (spec: MUST NOT transmit credentials in URIs)"
2643
+ };
2644
+ }
2645
+ return { passed: true, details: `HTTP ${res.statusCode} (token in query string not accepted)` };
2646
+ } catch {
2647
+ return { passed: true, details: "Connection rejected (acceptable)" };
2648
+ }
2649
+ }
2650
+ );
2651
+ await test(
2652
+ "security-cors-headers",
2653
+ "CORS headers are restrictive",
2654
+ "security",
2655
+ false,
2656
+ "basic/transports#streamable-http",
2657
+ async () => {
2658
+ try {
2659
+ const res = await request(backendUrl, {
2660
+ method: "OPTIONS",
2661
+ headers: {
2662
+ Origin: "https://evil.example.com",
2663
+ "Access-Control-Request-Method": "POST",
2664
+ ...buildHeaders()
2665
+ },
2666
+ signal: AbortSignal.timeout(Math.min(timeout, 5e3))
2667
+ });
2668
+ await res.body.text();
2669
+ const acao = res.headers["access-control-allow-origin"];
2670
+ if (!acao) {
2671
+ return { passed: true, details: "No CORS headers returned (server-to-server only, acceptable)" };
2672
+ }
2673
+ if (acao === "*") {
2674
+ return {
2675
+ passed: false,
2676
+ details: 'Access-Control-Allow-Origin is "*" (wildcard) \u2014 allows cross-origin credential theft'
2677
+ };
2678
+ }
2679
+ if (acao === "https://evil.example.com") {
2680
+ return { passed: false, details: "Server reflects arbitrary Origin in CORS \u2014 effectively wildcard" };
2681
+ }
2682
+ return { passed: true, details: `CORS restricted to: ${acao}` };
2683
+ } catch {
2684
+ return { passed: true, details: "OPTIONS request failed (no CORS, acceptable)" };
2685
+ }
2686
+ }
2687
+ );
2688
+ await test(
2689
+ "security-origin-validation",
2690
+ "Validates Origin header on requests",
2691
+ "security",
2692
+ false,
2693
+ "basic/transports#streamable-http",
2694
+ async () => {
2695
+ try {
2696
+ const res = await request(backendUrl, {
2697
+ method: "POST",
2698
+ headers: {
2699
+ "Content-Type": "application/json",
2700
+ Accept: "application/json, text/event-stream",
2701
+ Origin: "https://evil-rebinding-attack.example.com",
2702
+ ...buildHeaders()
2703
+ },
2704
+ body: JSON.stringify({ jsonrpc: "2.0", id: createIdCounter(99970)(), method: "ping" }),
2705
+ signal: AbortSignal.timeout(timeout)
2706
+ });
2707
+ await res.body.text();
2708
+ if (res.statusCode === 403 || res.statusCode === 401) {
2709
+ return { passed: true, details: `HTTP ${res.statusCode} (suspicious Origin rejected)` };
2710
+ }
2711
+ if (res.statusCode >= 200 && res.statusCode < 300) {
2712
+ return {
2713
+ passed: false,
2714
+ details: `HTTP ${res.statusCode} \u2014 server accepted request with untrusted Origin header (spec: MUST validate Origin for DNS rebinding protection)`
2715
+ };
2716
+ }
2717
+ if (res.statusCode >= 400) {
2718
+ return { passed: true, details: `HTTP ${res.statusCode} (suspicious Origin rejected)` };
2719
+ }
2720
+ return { passed: false, details: `HTTP ${res.statusCode}` };
2721
+ } catch {
2722
+ return { passed: true, details: "Connection rejected (acceptable)" };
2723
+ }
2724
+ }
2725
+ );
2726
+ async function runInjectionTest(toolName, paramName, payloads, detectPattern, label) {
2727
+ const issues = [];
2728
+ for (const payload of payloads) {
2729
+ try {
2730
+ const res = await rpc("tools/call", { name: toolName, arguments: { [paramName]: payload } });
2731
+ const content = res.body?.result?.content;
2732
+ if (Array.isArray(content)) {
2733
+ const text = content.map((c) => c.text || "").join(" ");
2734
+ if (detectPattern.test(text)) {
2735
+ issues.push(`Payload "${payload}" ${label} (output: ${text.substring(0, 100)})`);
2736
+ }
2737
+ }
2738
+ } catch {
2739
+ }
2740
+ }
2741
+ if (issues.length > 0) return { passed: false, details: issues.join("; ") };
2742
+ return {
2743
+ passed: true,
2744
+ details: `Tested ${payloads.length} payloads against ${toolName}.${paramName} \u2014 no ${label.split(" ")[0]} detected`
2745
+ };
2746
+ }
2747
+ if (toolNames.length > 0) {
2748
+ const allTools = cachedToolsList ?? [];
2749
+ const toolsWithStringParams = allTools.filter((t) => {
2750
+ const props = t.inputSchema?.properties;
2751
+ if (!props) return false;
2752
+ return Object.values(props).some((p) => p.type === "string");
2753
+ });
2754
+ const injectionTarget = toolsWithStringParams[0] || allTools[0];
2755
+ const targetStringParam = injectionTarget?.inputSchema?.properties ? Object.entries(injectionTarget.inputSchema.properties).find(
2756
+ ([_, v]) => v.type === "string"
2757
+ )?.[0] ?? null : null;
2758
+ await test(
2759
+ "security-command-injection",
2760
+ "Resists command injection in tool params",
2761
+ "security",
2762
+ false,
2763
+ "server/tools#calling-tools",
2764
+ async () => {
2765
+ if (!injectionTarget || !targetStringParam)
2766
+ return { passed: true, details: "No tools with string parameters to test" };
2767
+ return runInjectionTest(
2768
+ injectionTarget.name,
2769
+ targetStringParam,
2770
+ INJECTION_PAYLOADS.command,
2771
+ /root:.*:\d+:\d+:.*:\/|uid=\d+\(\w+\)|drwxr|pwned/i,
2772
+ "appears to have executed"
2773
+ );
2774
+ }
2775
+ );
2776
+ await test(
2777
+ "security-sql-injection",
2778
+ "Resists SQL injection in tool params",
2779
+ "security",
2780
+ false,
2781
+ "server/tools#calling-tools",
2782
+ async () => {
2783
+ if (!injectionTarget || !targetStringParam)
2784
+ return { passed: true, details: "No tools with string parameters to test" };
2785
+ return runInjectionTest(
2786
+ injectionTarget.name,
2787
+ targetStringParam,
2788
+ INJECTION_PAYLOADS.sql,
2789
+ /syntax error|sql|mysql|postgres|sqlite|information_schema|table_name/i,
2790
+ "triggered database error"
2791
+ );
2792
+ }
2793
+ );
2794
+ await test(
2795
+ "security-path-traversal",
2796
+ "Resists path traversal in tool params",
2797
+ "security",
2798
+ false,
2799
+ "server/tools#calling-tools",
2800
+ async () => {
2801
+ if (!injectionTarget || !targetStringParam)
2802
+ return { passed: true, details: "No tools with string parameters to test" };
2803
+ return runInjectionTest(
2804
+ injectionTarget.name,
2805
+ targetStringParam,
2806
+ INJECTION_PAYLOADS.pathTraversal,
2807
+ /root:.*:0:0|\[boot loader\]|\[extensions\]/i,
2808
+ "returned sensitive file content"
2809
+ );
2810
+ }
2811
+ );
2812
+ await test(
2813
+ "security-ssrf-internal",
2814
+ "Resists SSRF to internal networks",
2815
+ "security",
2816
+ false,
2817
+ "server/tools#calling-tools",
2818
+ async () => {
2819
+ const urlParamTool = allTools.find((t) => {
2820
+ const props = t.inputSchema?.properties;
2821
+ if (!props) return false;
2822
+ return Object.entries(props).some(
2823
+ ([k, v]) => v.type === "string" && /url|uri|endpoint|link|href/i.test(k)
2824
+ );
2825
+ });
2826
+ if (!urlParamTool) return { passed: true, details: "No tools with URL parameters found (skipped)" };
2827
+ const urlParam = Object.entries(urlParamTool.inputSchema.properties).find(
2828
+ ([k, v]) => v.type === "string" && /url|uri|endpoint|link|href/i.test(k)
2829
+ )?.[0];
2830
+ if (!urlParam) return { passed: true, details: "No URL parameter found" };
2831
+ return runInjectionTest(
2832
+ urlParamTool.name,
2833
+ urlParam,
2834
+ INJECTION_PAYLOADS.ssrf,
2835
+ /ami-|instance-id|hostname|iam|security-credentials/i,
2836
+ "returned internal data"
2837
+ );
2838
+ }
2839
+ );
2840
+ } else {
2841
+ for (const testId of [
2842
+ "security-command-injection",
2843
+ "security-sql-injection",
2844
+ "security-path-traversal",
2845
+ "security-ssrf-internal"
2846
+ ]) {
2847
+ await test(
2848
+ testId,
2849
+ TEST_DEFINITIONS_MAP.get(testId)?.name || testId,
2850
+ "security",
2851
+ false,
2852
+ "server/tools#calling-tools",
2853
+ async () => ({ passed: true, details: "No tools available to test (skipped)" })
2854
+ );
2855
+ }
2856
+ }
2857
+ await test(
2858
+ "security-oversized-input",
2859
+ "Handles oversized inputs gracefully",
2860
+ "security",
2861
+ false,
2862
+ "server/tools#calling-tools",
2863
+ async () => {
2864
+ const largeValue = "A".repeat(1048576);
2865
+ try {
2866
+ const res = await request(backendUrl, {
2867
+ method: "POST",
2868
+ headers: {
2869
+ "Content-Type": "application/json",
2870
+ Accept: "application/json, text/event-stream",
2871
+ ...buildHeaders()
2872
+ },
2873
+ body: JSON.stringify({
2874
+ jsonrpc: "2.0",
2875
+ id: nextId(),
2876
+ method: "tools/call",
2877
+ params: { name: toolNames[0] || "test", arguments: { data: largeValue } }
2878
+ }),
2879
+ signal: AbortSignal.timeout(timeout)
2880
+ });
2881
+ await res.body.text();
2882
+ if (res.statusCode === 413) {
2883
+ return { passed: true, details: "HTTP 413 Payload Too Large (good)" };
2884
+ }
2885
+ if (res.statusCode >= 400) {
2886
+ return { passed: true, details: `HTTP ${res.statusCode} (oversized input rejected)` };
2887
+ }
2888
+ return { passed: true, details: `HTTP ${res.statusCode} \u2014 server handled 1MB payload without crashing` };
2889
+ } catch (err) {
2890
+ const msg = err instanceof Error ? err.message : String(err);
2891
+ if (msg.includes("timeout") || msg.includes("abort")) {
2892
+ return { passed: false, details: "Request timed out \u2014 server may be struggling with oversized input" };
2893
+ }
2894
+ return { passed: true, details: "Connection rejected (acceptable for oversized input)" };
2895
+ }
2896
+ }
2897
+ );
2898
+ await test(
2899
+ "security-extra-params",
2900
+ "Rejects or ignores extra tool params",
2901
+ "security",
2902
+ false,
2903
+ "server/tools#calling-tools",
2904
+ async () => {
2905
+ if (toolNames.length === 0) {
2906
+ return { passed: true, details: "No tools available to test (skipped)" };
2907
+ }
2908
+ try {
2909
+ const res = await rpc("tools/call", {
2910
+ name: toolNames[0],
2911
+ arguments: { __injected_param__: "malicious_value", __proto__: { admin: true } }
2912
+ });
2913
+ const error = res.body?.error;
2914
+ if (error) {
2915
+ return { passed: true, details: `Extra params rejected with error: ${error.code} \u2014 ${error.message}` };
2916
+ }
2917
+ return { passed: true, details: "Server processed request (extra params likely ignored)" };
2918
+ } catch {
2919
+ return { passed: true, details: "Request rejected (acceptable)" };
2920
+ }
2921
+ }
2922
+ );
2923
+ await test(
2924
+ "security-tool-schema-defined",
2925
+ "All tools define inputSchema",
2926
+ "security",
2927
+ false,
2928
+ "server/tools#data-types",
2929
+ async () => {
2930
+ if (!toolsListOk) return { passed: true, details: "Skipped: tools/list not available" };
2931
+ const tools = cachedToolsList ?? [];
2932
+ if (tools.length === 0) return { passed: true, details: "No tools to validate" };
2933
+ const missing = tools.filter((t) => !t.inputSchema || t.inputSchema.type !== "object");
2934
+ if (missing.length > 0) {
2935
+ return {
2936
+ passed: false,
2937
+ details: `${missing.length} tool(s) missing inputSchema: ${missing.map((t) => t.name).join(", ")}`
2938
+ };
2939
+ }
2940
+ return { passed: true, details: `All ${tools.length} tool(s) have inputSchema defined` };
2941
+ }
2942
+ );
2943
+ await test(
2944
+ "security-tool-rug-pull",
2945
+ "Tool definitions are stable across calls",
2946
+ "security",
2947
+ false,
2948
+ "server/tools#listing-tools",
2949
+ async () => {
2950
+ if (!toolsListOk) return { passed: true, details: "Skipped: tools/list not available" };
2951
+ try {
2952
+ const res = await rpc("tools/list");
2953
+ const tools2 = res.body?.result?.tools;
2954
+ if (!Array.isArray(tools2)) return { passed: false, details: "Second tools/list call failed" };
2955
+ const tools1 = cachedToolsList ?? [];
2956
+ if (tools1.length !== tools2.length) {
2957
+ return {
2958
+ passed: false,
2959
+ details: `Tool count changed: ${tools1.length} \u2192 ${tools2.length} (possible rug-pull)`
2960
+ };
2961
+ }
2962
+ const names1 = tools1.map((t) => t.name).sort().join(",");
2963
+ const names2 = tools2.map((t) => t.name).sort().join(",");
2964
+ if (names1 !== names2) {
2965
+ return { passed: false, details: "Tool names changed between calls (possible rug-pull)" };
2966
+ }
2967
+ for (const t1 of tools1) {
2968
+ const t2 = tools2.find((t) => t.name === t1.name);
2969
+ if (t2 && t1.description !== t2.description) {
2970
+ return {
2971
+ passed: false,
2972
+ details: `Tool "${t1.name}" description changed between calls (possible rug-pull)`
2973
+ };
2974
+ }
2975
+ }
2976
+ return { passed: true, details: `${tools1.length} tool(s) consistent across 2 calls` };
2977
+ } catch {
2978
+ return { passed: false, details: "Second tools/list call threw an error" };
2979
+ }
2980
+ }
2981
+ );
2982
+ await test(
2983
+ "security-tool-description-poisoning",
2984
+ "Tool descriptions free of injection patterns",
2985
+ "security",
2986
+ false,
2987
+ "server/tools#data-types",
2988
+ async () => {
2989
+ if (!toolsListOk) return { passed: true, details: "Skipped: tools/list not available" };
2990
+ const tools = cachedToolsList ?? [];
2991
+ if (tools.length === 0) return { passed: true, details: "No tools to validate" };
2992
+ const suspiciousPatterns = [
2993
+ { pattern: /ignore\s+(all\s+)?previous/i, label: "ignore previous instructions" },
2994
+ { pattern: /override\s+(system|instructions|rules)/i, label: "override instructions" },
2995
+ { pattern: /system\s+prompt/i, label: "system prompt reference" },
2996
+ { pattern: /you\s+must\s+(always|never)/i, label: "behavioral override" },
2997
+ { pattern: /do\s+not\s+(tell|inform|mention)/i, label: "concealment instruction" },
2998
+ { pattern: /\b[A-Za-z0-9+/]{40,}={0,2}\b/, label: "possible Base64-encoded payload" },
2999
+ // Zero-width characters (U+200B, U+200C, U+200D, U+FEFF)
3000
+ { pattern: /\u200B|\u200C|\u200D|\uFEFF/, label: "hidden Unicode characters" }
3001
+ ];
3002
+ const issues = [];
3003
+ for (const tool of tools) {
3004
+ const textsToCheck = [
3005
+ tool.description || "",
3006
+ ...tool.inputSchema?.properties ? Object.values(tool.inputSchema.properties).map((p) => p.description || "") : []
3007
+ ];
3008
+ const combined = textsToCheck.join(" ");
3009
+ for (const { pattern, label } of suspiciousPatterns) {
3010
+ if (pattern.test(combined)) {
3011
+ issues.push(`Tool "${tool.name}": ${label}`);
3012
+ }
3013
+ }
3014
+ }
3015
+ if (issues.length > 0) return { passed: false, details: issues.join("; ") };
3016
+ return { passed: true, details: `${tools.length} tool(s) scanned \u2014 no injection patterns found` };
3017
+ }
3018
+ );
3019
+ await test(
3020
+ "security-tool-cross-reference",
3021
+ "Tools do not reference other tools by name",
3022
+ "security",
3023
+ false,
3024
+ "server/tools#data-types",
3025
+ async () => {
3026
+ if (!toolsListOk) return { passed: true, details: "Skipped: tools/list not available" };
3027
+ const tools = cachedToolsList ?? [];
3028
+ if (tools.length < 2)
3029
+ return { passed: true, details: "Fewer than 2 tools \u2014 cross-reference check not applicable" };
3030
+ const names = tools.map((t) => t.name).filter(Boolean);
3031
+ const issues = [];
3032
+ for (const tool of tools) {
3033
+ const desc = (tool.description || "").toLowerCase();
3034
+ for (const otherName of names) {
3035
+ if (otherName === tool.name) continue;
3036
+ if (desc.includes(otherName.toLowerCase())) {
3037
+ issues.push(`Tool "${tool.name}" description references "${otherName}"`);
3038
+ }
3039
+ }
3040
+ }
3041
+ if (issues.length > 0) {
3042
+ warnings.push(`Cross-tool references found: ${issues.join("; ")}`);
3043
+ return { passed: false, details: issues.join("; ") };
3044
+ }
3045
+ return { passed: true, details: `${tools.length} tool(s) checked \u2014 no cross-references found` };
3046
+ }
3047
+ );
3048
+ await test(
3049
+ "security-error-no-stacktrace",
3050
+ "Error responses do not leak stack traces",
3051
+ "security",
3052
+ false,
3053
+ "basic",
3054
+ async () => {
3055
+ const errorResponses = [];
3056
+ const errorPayloads = [
3057
+ "{this is not valid json!!!",
3058
+ JSON.stringify({ jsonrpc: "2.0", id: nextId(), method: "nonexistent/___crash___test___" }),
3059
+ JSON.stringify({
3060
+ jsonrpc: "2.0",
3061
+ id: nextId(),
3062
+ method: "tools/call",
3063
+ params: { name: "___nonexistent___tool___" }
3064
+ })
3065
+ ];
3066
+ for (const payload of errorPayloads) {
3067
+ try {
3068
+ const res = await request(backendUrl, {
3069
+ method: "POST",
3070
+ headers: {
3071
+ "Content-Type": "application/json",
3072
+ Accept: "application/json, text/event-stream",
3073
+ ...buildHeaders()
3074
+ },
3075
+ body: payload,
3076
+ signal: AbortSignal.timeout(timeout)
3077
+ });
3078
+ const text = await res.body.text();
3079
+ errorResponses.push(text);
3080
+ } catch {
3081
+ }
3082
+ }
3083
+ const issues = [];
3084
+ for (const text of errorResponses) {
3085
+ for (const pattern of STACK_TRACE_PATTERNS) {
3086
+ if (pattern.test(text)) {
3087
+ issues.push(`Response contains: ${pattern.source} (matched in: ${text.substring(0, 80)}...)`);
3088
+ break;
3089
+ }
3090
+ }
3091
+ }
3092
+ if (issues.length > 0) return { passed: false, details: issues.slice(0, 3).join("; ") };
3093
+ return {
3094
+ passed: true,
3095
+ details: `${errorResponses.length} error responses checked \u2014 no stack traces or sensitive data found`
3096
+ };
3097
+ }
3098
+ );
3099
+ await test(
3100
+ "security-error-no-internal-ip",
3101
+ "Error responses do not leak internal IPs",
3102
+ "security",
3103
+ false,
3104
+ "basic",
3105
+ async () => {
3106
+ try {
3107
+ const res = await request(backendUrl, {
3108
+ method: "POST",
3109
+ headers: {
3110
+ "Content-Type": "application/json",
3111
+ Accept: "application/json, text/event-stream",
3112
+ ...buildHeaders()
3113
+ },
3114
+ body: JSON.stringify({ jsonrpc: "2.0", id: nextId(), method: "___trigger_error___" }),
3115
+ signal: AbortSignal.timeout(timeout)
3116
+ });
3117
+ const text = await res.body.text();
3118
+ for (const pattern of INTERNAL_IP_PATTERNS) {
3119
+ const match = text.match(pattern);
3120
+ if (match) {
3121
+ return { passed: false, details: `Error response contains internal IP: ${match[0]}` };
3122
+ }
3123
+ }
3124
+ return { passed: true, details: "No internal IP addresses found in error responses" };
3125
+ } catch {
3126
+ return { passed: true, details: "No response to check (connection error)" };
3127
+ }
3128
+ }
3129
+ );
3130
+ await test(
3131
+ "security-rate-limiting",
3132
+ "Rate limiting is enforced",
3133
+ "security",
3134
+ false,
3135
+ "basic/transports#streamable-http",
3136
+ async () => {
3137
+ const burstSize = 50;
3138
+ let got429 = false;
3139
+ const promises = Array.from(
3140
+ { length: burstSize },
3141
+ () => mcpRequest(backendUrl, "ping", void 0, nextId, buildHeaders(), timeout).then((res) => {
3142
+ if (res.statusCode === 429) got429 = true;
3143
+ return res.statusCode;
3144
+ }).catch(() => 0)
3145
+ );
3146
+ const statusCodes = await Promise.all(promises);
3147
+ if (got429) {
3148
+ return { passed: true, details: `Rate limiting detected (429 returned after ${burstSize} rapid requests)` };
3149
+ }
3150
+ const errorCount = statusCodes.filter((c) => c >= 500).length;
3151
+ if (errorCount > burstSize / 2) {
3152
+ return {
3153
+ passed: false,
3154
+ details: `Server returned ${errorCount}/${burstSize} 5xx errors under load \u2014 should return 429 instead of crashing`
3155
+ };
3156
+ }
3157
+ return {
3158
+ passed: false,
3159
+ details: `No rate limiting detected (${burstSize} rapid requests all returned ${[...new Set(statusCodes)].join(",")})`
3160
+ };
3161
+ }
3162
+ );
1814
3163
  await test(
1815
3164
  "transport-delete",
1816
3165
  "DELETE accepted or returns 405",