@langwatch/mcp-server 0.10.1 → 2.0.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.
Files changed (144) hide show
  1. package/.python-version +1 -0
  2. package/.release-please-shim +1 -1
  3. package/CHANGELOG.md +75 -0
  4. package/CONTRIBUTING.md +1 -1
  5. package/README.md +64 -18
  6. package/dist/{archive-project-KAZFHR4A.js → archive-project-4EQGLBJJ.js} +5 -4
  7. package/dist/{archive-scenario-6M2IB7Y2.js → archive-scenario-W6BXYDZ3.js} +5 -4
  8. package/dist/{archive-suite-NXZ3YDS3.js → archive-suite-4T6BSRS7.js} +5 -4
  9. package/dist/{assign-prompt-tag-WPUJO55U.js → assign-prompt-tag-VLXUWEKU.js} +4 -3
  10. package/dist/chunk-37SMPMQS.js +12 -0
  11. package/dist/{chunk-HRFQAFPR.js → chunk-4QC7SA2L.js} +221 -134
  12. package/dist/{chunk-XRQNXN2Z.js → chunk-5CCZFUXS.js} +2 -2
  13. package/dist/{chunk-ITN2QGHF.js → chunk-77BNWQ3U.js} +2 -2
  14. package/dist/{chunk-B6UV3JVI.js → chunk-7RHG56OH.js} +2 -2
  15. package/dist/{chunk-CAY57CKF.js → chunk-A2LEVYQ5.js} +78 -5
  16. package/dist/{chunk-U2QIW2SW.js → chunk-AQJO2EI5.js} +2 -2
  17. package/dist/{chunk-GWEW5XON.js → chunk-CDYQOY5U.js} +2 -2
  18. package/dist/{chunk-LTEJDL4V.js → chunk-J42FWRJ2.js} +2 -2
  19. package/dist/chunk-SAS5OB7F.js +58 -0
  20. package/dist/{chunk-AGGE6NPR.js → chunk-SFB4MU6H.js} +2 -2
  21. package/dist/{chunk-COCNCXVJ.js → chunk-TJCXFNDT.js} +2 -2
  22. package/dist/chunk-TOXJQDIZ.js +432 -0
  23. package/dist/chunk-UJPXFA26.js +267 -0
  24. package/dist/{chunk-KOO5733S.js → chunk-WT4PO4A3.js} +8 -2
  25. package/dist/{chunk-RDUXCCFR.js → chunk-YX3A3CFM.js} +2 -2
  26. package/dist/{chunk-UKRCZJJC.js → chunk-YZLYHLLI.js} +2 -2
  27. package/dist/{chunk-ESGZVPPC.js → chunk-ZWIL4EFL.js} +2 -2
  28. package/dist/config.js +2 -1
  29. package/dist/{create-agent-BI7UTJ6A.js → create-agent-7XHO6UIS.js} +5 -4
  30. package/dist/{create-annotation-SNM2J6S4.js → create-annotation-YQXRQC6A.js} +5 -4
  31. package/dist/{create-api-key-23MXYC2L.js → create-api-key-YUS36KBU.js} +5 -4
  32. package/dist/{create-dashboard-CPOOOIKK.js → create-dashboard-4Z5JO5LB.js} +5 -4
  33. package/dist/{create-dataset-BVXPVVY2.js → create-dataset-E6NMSVX7.js} +5 -4
  34. package/dist/{create-dataset-records-S7VFIIMR.js → create-dataset-records-SKHPRD2K.js} +5 -4
  35. package/dist/{create-evaluator-WJAAQOUE.js → create-evaluator-JXF5PF33.js} +5 -4
  36. package/dist/create-mcp-server.js +4 -3
  37. package/dist/{create-project-BF7LMZH5.js → create-project-CS2CB57Y.js} +5 -4
  38. package/dist/{create-prompt-LZ3QHSU4.js → create-prompt-F5RMX3L3.js} +4 -3
  39. package/dist/{create-prompt-tag-IF4J24QM.js → create-prompt-tag-GMRWTEFR.js} +4 -3
  40. package/dist/{create-scenario-BK4E5DEU.js → create-scenario-JDR2VB2H.js} +5 -4
  41. package/dist/{create-suite-HEQPNLND.js → create-suite-LZS6QIAF.js} +5 -4
  42. package/dist/{delete-agent-Y4T2G5PT.js → delete-agent-O3EEH4S5.js} +5 -4
  43. package/dist/{delete-annotation-KYDMQTZG.js → delete-annotation-XP6FQM7A.js} +5 -4
  44. package/dist/{delete-dashboard-3RW647WJ.js → delete-dashboard-RFUNYCNP.js} +5 -4
  45. package/dist/{delete-dataset-SZAHFHHS.js → delete-dataset-3MJFRDLP.js} +5 -4
  46. package/dist/{delete-dataset-records-ISHKGEBH.js → delete-dataset-records-WPMU5GL5.js} +5 -4
  47. package/dist/{delete-evaluator-VKIG5I3S.js → delete-evaluator-33SP2JFX.js} +5 -4
  48. package/dist/{delete-prompt-tag-VYYL4GTF.js → delete-prompt-tag-KNMZVSPB.js} +4 -3
  49. package/dist/{delete-workflow-SHNPYSWQ.js → delete-workflow-3NUXO46U.js} +5 -4
  50. package/dist/discover-evaluator-schema-XTAD4X7D.js +2191 -0
  51. package/dist/{discover-scenario-schema-MEEEVND7.js → discover-scenario-schema-FE64QK2D.js} +3 -1
  52. package/dist/{discover-schema-3T52ORPB.js → discover-schema-L6QDPON3.js} +3 -1
  53. package/dist/{get-agent-IZSP7AR5.js → get-agent-Y7MWZ65F.js} +5 -4
  54. package/dist/{get-analytics-EDFAYYIQ.js → get-analytics-TETCSOK6.js} +4 -3
  55. package/dist/{get-dashboard-WSAO6IQ4.js → get-dashboard-KHBEGZGL.js} +5 -4
  56. package/dist/{get-dataset-BEVNXQNF.js → get-dataset-RCMU5VAH.js} +5 -4
  57. package/dist/{get-evaluator-HCVXNPZR.js → get-evaluator-ADMKVWYZ.js} +5 -4
  58. package/dist/{get-project-H4V3GYRQ.js → get-project-RAK7URQJ.js} +5 -4
  59. package/dist/{get-prompt-EWRJVVGB.js → get-prompt-OY5B7TRI.js} +4 -3
  60. package/dist/{get-scenario-24YUJS5W.js → get-scenario-ZTAJJL5T.js} +5 -4
  61. package/dist/{get-simulation-run-UX2W6F6I.js → get-simulation-run-T2ZQWYH2.js} +5 -4
  62. package/dist/{get-suite-B65ZKZJA.js → get-suite-J7JVWO6O.js} +5 -4
  63. package/dist/{get-trace-ZR7MIITH.js → get-trace-K7U234Q4.js} +8 -10
  64. package/dist/{get-workflow-YROHUQJW.js → get-workflow-L5L2PSK3.js} +5 -4
  65. package/dist/http-security-EU3CHTY7.js +26 -0
  66. package/dist/http-server-YXHFPPGA.js +24706 -0
  67. package/dist/index.js +23280 -3135
  68. package/dist/{langwatch-api-annotations-OPEXNTPF.js → langwatch-api-annotations-FDAS6NQ7.js} +5 -4
  69. package/dist/{langwatch-api-dashboards-NPQM6QJI.js → langwatch-api-dashboards-JTVCS7ZJ.js} +5 -4
  70. package/dist/{langwatch-api-monitors-3L25OOOS.js → langwatch-api-monitors-3J7UIQME.js} +4 -3
  71. package/dist/{langwatch-api-secrets-ZFURUA62.js → langwatch-api-secrets-BUBSNCNO.js} +4 -3
  72. package/dist/{langwatch-api-triggers-XGXXT7DD.js → langwatch-api-triggers-EDFUCJN6.js} +4 -3
  73. package/dist/langwatch-api-workflows-NBJX5KOG.js +16 -0
  74. package/dist/{list-agents-6ZNOV7FK.js → list-agents-KFHKGPXV.js} +5 -4
  75. package/dist/{list-annotations-6P3IWILH.js → list-annotations-ZTVP4EEL.js} +5 -4
  76. package/dist/{list-api-keys-JJI62KD2.js → list-api-keys-CWD4UQT5.js} +5 -4
  77. package/dist/{list-dashboards-G2WJOXWB.js → list-dashboards-PWG6P6KR.js} +5 -4
  78. package/dist/{list-dataset-records-GWWVOCII.js → list-dataset-records-IOE7LQXS.js} +5 -4
  79. package/dist/{list-datasets-HBTH33X4.js → list-datasets-ZT4JYUDT.js} +5 -4
  80. package/dist/{list-evaluators-K5OGB6TX.js → list-evaluators-SJHC7VBH.js} +5 -4
  81. package/dist/{list-model-providers-JMOGZLSO.js → list-model-providers-PPD2WPD2.js} +5 -4
  82. package/dist/{list-projects-OXJC2NW5.js → list-projects-K7QAIX2I.js} +5 -4
  83. package/dist/{list-prompt-tags-J2HPHVAZ.js → list-prompt-tags-FOO6TNHB.js} +4 -3
  84. package/dist/{list-prompts-C7GR72XL.js → list-prompts-SC2HAUFG.js} +4 -3
  85. package/dist/{list-scenarios-JEPGIIDO.js → list-scenarios-F2WYNRIE.js} +5 -4
  86. package/dist/{list-simulation-runs-DRSAGPEC.js → list-simulation-runs-KF5THG5H.js} +5 -4
  87. package/dist/{list-suites-POTZ3ZT6.js → list-suites-CRY4VWW6.js} +5 -4
  88. package/dist/{list-workflows-QQZQIOHB.js → list-workflows-QSJWURCK.js} +5 -4
  89. package/dist/{rename-prompt-tag-4AAV2BS4.js → rename-prompt-tag-EKWU5QF3.js} +4 -3
  90. package/dist/report-issue-XYVAPAYJ.js +412 -0
  91. package/dist/{revoke-api-key-TONB4ADQ.js → revoke-api-key-FTRTZMOF.js} +5 -4
  92. package/dist/{run-agent-7QE3YEH7.js → run-agent-6SM4XNA7.js} +5 -4
  93. package/dist/{run-suite-Q66OSPO4.js → run-suite-NKZCJ2IN.js} +5 -4
  94. package/dist/{run-workflow-RWX2D752.js → run-workflow-QPXC627O.js} +5 -4
  95. package/dist/{search-traces-M5E5VB4X.js → search-traces-A6HFKPLJ.js} +10 -3
  96. package/dist/{set-model-provider-XENT5D2P.js → set-model-provider-3WKT63ZN.js} +5 -4
  97. package/dist/{update-agent-GML25EE3.js → update-agent-SMAEHLXH.js} +5 -4
  98. package/dist/{update-dataset-R4MM6NNY.js → update-dataset-BDUK7TUO.js} +5 -4
  99. package/dist/{update-dataset-record-FN4BL5P4.js → update-dataset-record-4ZSDRBSW.js} +5 -4
  100. package/dist/{update-evaluator-LH2RDDB5.js → update-evaluator-LS6TIBY7.js} +5 -4
  101. package/dist/{update-project-H53IHRBB.js → update-project-LKVYXENH.js} +5 -4
  102. package/dist/{update-prompt-M33OTTAJ.js → update-prompt-ODCRQRN6.js} +4 -3
  103. package/dist/{update-scenario-FKTQRAFQ.js → update-scenario-NEXCAQI7.js} +5 -4
  104. package/dist/{update-suite-JJTNOTXN.js → update-suite-SNO3GS7T.js} +5 -4
  105. package/package.json +20 -18
  106. package/pyproject.toml +10 -2
  107. package/src/__tests__/all-tools.integration.test.ts +56 -120
  108. package/src/__tests__/config.unit.test.ts +33 -0
  109. package/src/__tests__/docker.integration.test.ts +91 -7
  110. package/src/__tests__/documentation-fetch-security.integration.test.ts +182 -0
  111. package/src/__tests__/feature-map-tool-drift.unit.test.ts +93 -0
  112. package/src/__tests__/http-security-origin.unit.test.ts +97 -0
  113. package/src/__tests__/http-security-sessions.unit.test.ts +209 -0
  114. package/src/__tests__/http-security-verifier.unit.test.ts +248 -0
  115. package/src/__tests__/http-server-allocation.integration.test.ts +279 -0
  116. package/src/__tests__/http-server-origin.integration.test.ts +169 -0
  117. package/src/__tests__/http-server-session-auth.integration.test.ts +341 -0
  118. package/src/__tests__/http-transport.integration.test.ts +85 -87
  119. package/src/__tests__/langwatch-api.unit.test.ts +206 -0
  120. package/src/__tests__/public-http-request-security.integration.test.ts +118 -0
  121. package/src/__tests__/report-issue.integration.test.ts +147 -0
  122. package/src/__tests__/support/http-server-harness.ts +138 -0
  123. package/src/__tests__/tools.unit.test.ts +24 -0
  124. package/src/config.ts +17 -2
  125. package/src/create-mcp-server.ts +43 -29
  126. package/src/documentation-fetch.ts +111 -0
  127. package/src/http-security.ts +492 -0
  128. package/src/http-server.ts +536 -152
  129. package/src/index.ts +49 -2
  130. package/src/langwatch-api-agents.ts +2 -2
  131. package/src/langwatch-api.ts +138 -8
  132. package/src/public-http-request.ts +242 -0
  133. package/src/tools/discover-evaluator-schema.ts +2 -2
  134. package/src/tools/get-trace.ts +2 -12
  135. package/src/tools/report-issue.ts +150 -0
  136. package/src/tools/search-traces.ts +4 -0
  137. package/src/utils/format-evaluations.ts +20 -0
  138. package/tsconfig.json +8 -1
  139. package/uv.lock +261 -207
  140. package/dist/chunk-IUP5IHBD.js +0 -71
  141. package/dist/discover-evaluator-schema-H23XCLNE.js +0 -1402
  142. package/dist/http-server-GXVEDA7G.js +0 -226
  143. package/dist/langwatch-api-workflows-CXCTTCXT.js +0 -15
  144. package/pnpm-workspace.yaml +0 -17
@@ -452,4 +452,210 @@ describe("langwatch-api", () => {
452
452
  ).rejects.toThrow("Forbidden: invalid API key");
453
453
  });
454
454
  });
455
+
456
+ describe("when the API returns a handled-error JSON body", () => {
457
+ const handledErrorBody = {
458
+ error: "invalid_filter",
459
+ message: "Filter 'llm.model' is not supported",
460
+ tips: ["Use 'metadata.model' instead", "See the filter reference"],
461
+ docsUrl: "https://docs.langwatch.ai/api/filters",
462
+ fault: "customer",
463
+ };
464
+
465
+ it("parses code, tips, docsUrl and fault into LangWatchApiError fields", async () => {
466
+ const { searchTraces, LangWatchApiError } = await import(
467
+ "../langwatch-api.js"
468
+ );
469
+ mockErrorResponse(400, JSON.stringify(handledErrorBody));
470
+
471
+ const error = await searchTraces({
472
+ startDate: 1000,
473
+ endDate: 2000,
474
+ }).catch((e) => e);
475
+
476
+ expect(error).toBeInstanceOf(LangWatchApiError);
477
+ expect(error.status).toBe(400);
478
+ expect(error.responseBody).toBe(JSON.stringify(handledErrorBody));
479
+ expect(error.code).toBe("invalid_filter");
480
+ expect(error.tips).toEqual(handledErrorBody.tips);
481
+ expect(error.docsUrl).toBe(handledErrorBody.docsUrl);
482
+ expect(error.fault).toBe("customer");
483
+ });
484
+
485
+ it("formats the message with the server message, Tips section and Docs link", async () => {
486
+ const { searchTraces } = await import("../langwatch-api.js");
487
+ mockErrorResponse(400, JSON.stringify(handledErrorBody));
488
+
489
+ const error = await searchTraces({
490
+ startDate: 1000,
491
+ endDate: 2000,
492
+ }).catch((e) => e);
493
+
494
+ expect(error.message).toContain(
495
+ "LangWatch API error 400: Filter 'llm.model' is not supported"
496
+ );
497
+ expect(error.message).toContain("Tips:");
498
+ expect(error.message).toContain("- Use 'metadata.model' instead");
499
+ expect(error.message).toContain("- See the filter reference");
500
+ expect(error.message).toContain(
501
+ "Docs: https://docs.langwatch.ai/api/filters"
502
+ );
503
+ });
504
+
505
+ // A validation failure names the offending field AND the values it would
506
+ // have taken, in `reasons[].meta`. Dropping that leaves the message's own
507
+ // advice ("pick one of the types in this error's expected list") naming a
508
+ // list the caller was never given.
509
+ describe("when the failure carries the values it would have accepted", () => {
510
+ const rejectedTypeBody = {
511
+ error: "validation_error",
512
+ message:
513
+ "Unknown evaluator type. Pick one of the types in this error's expected list and retry.",
514
+ reasons: [
515
+ {
516
+ code: "schema_failure",
517
+ kind: "schema_failure",
518
+ meta: {
519
+ field: "config.evaluatorType",
520
+ expected: ["ragas/response_relevancy", "langevals/llm_boolean"],
521
+ received: "ragas/answer_relevancy",
522
+ },
523
+ },
524
+ ],
525
+ };
526
+
527
+ /** @scenario A rejection over MCP carries the accepted types */
528
+ it("keeps the reasons on the error", async () => {
529
+ const { createEvaluator } = await import(
530
+ "../langwatch-api-evaluators.js"
531
+ );
532
+ mockErrorResponse(422, JSON.stringify(rejectedTypeBody));
533
+
534
+ const error = await createEvaluator({
535
+ name: "Relevancy",
536
+ config: { evaluatorType: "ragas/answer_relevancy" },
537
+ }).catch((e) => e);
538
+
539
+ expect(error.reasons).toEqual(rejectedTypeBody.reasons);
540
+ });
541
+
542
+ it("names the rejected field and the accepted values in the message", async () => {
543
+ const { createEvaluator } = await import(
544
+ "../langwatch-api-evaluators.js"
545
+ );
546
+ mockErrorResponse(422, JSON.stringify(rejectedTypeBody));
547
+
548
+ const error = await createEvaluator({
549
+ name: "Relevancy",
550
+ config: { evaluatorType: "ragas/answer_relevancy" },
551
+ }).catch((e) => e);
552
+
553
+ expect(error.message).toContain("config.evaluatorType");
554
+ expect(error.message).toContain("ragas/response_relevancy");
555
+ expect(error.message).toContain("langevals/llm_boolean");
556
+ expect(error.message).toContain("ragas/answer_relevancy");
557
+ });
558
+ });
559
+
560
+ it("parses the tRPC shape using `code` instead of `error`", async () => {
561
+ const { searchTraces } = await import("../langwatch-api.js");
562
+ const body = {
563
+ code: "dataset_not_found",
564
+ message: "Dataset 'abc' not found",
565
+ meta: { datasetId: "abc" },
566
+ httpStatus: 404,
567
+ fault: "customer",
568
+ tips: ["Check the dataset slug"],
569
+ docsUrl: "https://docs.langwatch.ai/datasets",
570
+ reasons: [],
571
+ };
572
+ mockErrorResponse(404, JSON.stringify(body));
573
+
574
+ const error = await searchTraces({
575
+ startDate: 1000,
576
+ endDate: 2000,
577
+ }).catch((e) => e);
578
+
579
+ expect(error.code).toBe("dataset_not_found");
580
+ expect(error.tips).toEqual(["Check the dataset slug"]);
581
+ expect(error.docsUrl).toBe("https://docs.langwatch.ai/datasets");
582
+ expect(error.fault).toBe("customer");
583
+ expect(error.message).toContain("Dataset 'abc' not found");
584
+ });
585
+
586
+ it("omits the Tips and Docs sections when absent", async () => {
587
+ const { searchTraces } = await import("../langwatch-api.js");
588
+ mockErrorResponse(
589
+ 401,
590
+ JSON.stringify({ error: "unauthorized", message: "Invalid API key" })
591
+ );
592
+
593
+ const error = await searchTraces({
594
+ startDate: 1000,
595
+ endDate: 2000,
596
+ }).catch((e) => e);
597
+
598
+ expect(error.code).toBe("unauthorized");
599
+ expect(error.tips).toBeUndefined();
600
+ expect(error.docsUrl).toBeUndefined();
601
+ expect(error.fault).toBeUndefined();
602
+ expect(error.message).toBe(
603
+ "LangWatch API error 401: Invalid API key"
604
+ );
605
+ });
606
+
607
+ it("ignores an invalid fault value", async () => {
608
+ const { searchTraces } = await import("../langwatch-api.js");
609
+ mockErrorResponse(
610
+ 500,
611
+ JSON.stringify({ error: "boom", message: "Boom", fault: "nobody" })
612
+ );
613
+
614
+ const error = await searchTraces({
615
+ startDate: 1000,
616
+ endDate: 2000,
617
+ }).catch((e) => e);
618
+
619
+ expect(error.fault).toBeUndefined();
620
+ });
621
+ });
622
+
623
+ describe("when the error body is not a handled-error envelope", () => {
624
+ it("keeps the raw text as the message and sets no extra fields", async () => {
625
+ const { searchTraces, LangWatchApiError } = await import(
626
+ "../langwatch-api.js"
627
+ );
628
+ mockErrorResponse(502, "<html>Bad Gateway</html>");
629
+
630
+ const error = await searchTraces({
631
+ startDate: 1000,
632
+ endDate: 2000,
633
+ }).catch((e) => e);
634
+
635
+ expect(error).toBeInstanceOf(LangWatchApiError);
636
+ expect(error.status).toBe(502);
637
+ expect(error.responseBody).toBe("<html>Bad Gateway</html>");
638
+ expect(error.message).toBe(
639
+ "LangWatch API error 502: <html>Bad Gateway</html>"
640
+ );
641
+ expect(error.code).toBeUndefined();
642
+ expect(error.tips).toBeUndefined();
643
+ expect(error.docsUrl).toBeUndefined();
644
+ expect(error.fault).toBeUndefined();
645
+ });
646
+
647
+ it("treats JSON without error/code/message fields as raw text", async () => {
648
+ const { searchTraces } = await import("../langwatch-api.js");
649
+ const body = JSON.stringify({ unexpected: true });
650
+ mockErrorResponse(500, body);
651
+
652
+ const error = await searchTraces({
653
+ startDate: 1000,
654
+ endDate: 2000,
655
+ }).catch((e) => e);
656
+
657
+ expect(error.code).toBeUndefined();
658
+ expect(error.message).toBe(`LangWatch API error 500: ${body}`);
659
+ });
660
+ });
455
661
  });
@@ -0,0 +1,118 @@
1
+ import { createServer, type Server } from "node:http";
2
+ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
3
+
4
+ import {
5
+ headersForRedirect,
6
+ requestPublicJson,
7
+ resolvePublicDestination,
8
+ } from "../public-http-request.js";
9
+
10
+ describe("public HTTP request security", () => {
11
+ afterEach(() => {
12
+ vi.useRealTimers();
13
+ });
14
+
15
+ /** @scenario Running an HTTP agent rejects unsafe destinations */
16
+ it.each([
17
+ "http://127.0.0.1/secrets",
18
+ "http://2130706433/secrets",
19
+ "http://169.254.169.254/latest/meta-data/",
20
+ "http://10.0.0.1/internal",
21
+ "http://[::1]/secrets",
22
+ "file:///etc/passwd",
23
+ "http://user:password@example.com/",
24
+ ])("rejects unsafe destination %s", async (url) => {
25
+ await expect(resolvePublicDestination(url)).rejects.toThrow(/globally routable public addresses/);
26
+ });
27
+
28
+ it("fails closed when any resolved address is not public", async () => {
29
+ await expect(
30
+ resolvePublicDestination("https://agent.example/run", async () => [
31
+ { address: "93.184.216.34", family: 4 },
32
+ { address: "10.0.0.4", family: 4 },
33
+ ])
34
+ ).rejects.toThrow(/globally routable public addresses/);
35
+ });
36
+
37
+ it("pins a validated public destination", async () => {
38
+ await expect(
39
+ resolvePublicDestination("https://agent.example/run", async () => [{ address: "93.184.216.34", family: 4 }])
40
+ ).resolves.toMatchObject({
41
+ address: "93.184.216.34",
42
+ family: 4,
43
+ });
44
+ });
45
+
46
+ it("bounds DNS resolution time", async () => {
47
+ vi.useFakeTimers();
48
+ const resolution = resolvePublicDestination(
49
+ "https://agent.example/run",
50
+ () => new Promise(() => undefined)
51
+ );
52
+ const rejection = expect(resolution).rejects.toThrow(
53
+ /destination could not be resolved/
54
+ );
55
+
56
+ await vi.advanceTimersByTimeAsync(30_000);
57
+
58
+ await rejection;
59
+ });
60
+
61
+ /** @scenario HTTP agent redirects are revalidated */
62
+ it("rejects private redirect targets and strips cross-origin secrets", async () => {
63
+ await expect(
64
+ resolvePublicDestination("http://127.0.0.1/redirect-target")
65
+ ).rejects.toThrow(/globally routable public addresses/);
66
+
67
+ expect(
68
+ headersForRedirect(
69
+ {
70
+ Authorization: "Bearer secret",
71
+ Cookie: "session=secret",
72
+ "Content-Type": "application/json",
73
+ "X-Api-Key": "secret",
74
+ "X-Request-Id": "request-1",
75
+ },
76
+ true
77
+ )
78
+ ).toEqual({
79
+ "Content-Type": "application/json",
80
+ "X-Request-Id": "request-1",
81
+ });
82
+ });
83
+
84
+ describe("real HTTP request", () => {
85
+ let server: Server;
86
+ let port: number;
87
+ let hits = 0;
88
+
89
+ beforeAll(async () => {
90
+ server = createServer((_request, response) => {
91
+ hits += 1;
92
+ response.setHeader("Content-Type", "application/json");
93
+ response.end(JSON.stringify({ secret: true }));
94
+ });
95
+ await new Promise<void>((resolve) => {
96
+ server.listen(0, "127.0.0.1", resolve);
97
+ });
98
+ const address = server.address();
99
+ port = typeof address === "object" && address ? address.port : 0;
100
+ });
101
+
102
+ afterAll(async () => {
103
+ await new Promise<void>((resolve, reject) => {
104
+ server.close((error) => (error ? reject(error) : resolve()));
105
+ });
106
+ });
107
+
108
+ it("blocks loopback before opening a connection", async () => {
109
+ await expect(
110
+ requestPublicJson(`http://127.0.0.1:${port}/secrets`, {
111
+ method: "POST",
112
+ body: "{}",
113
+ })
114
+ ).rejects.toThrow(/globally routable public addresses/);
115
+ expect(hits).toBe(0);
116
+ });
117
+ });
118
+ });
@@ -0,0 +1,147 @@
1
+ import { createServer, type Server } from "node:http";
2
+ import type { AddressInfo } from "node:net";
3
+ import {
4
+ afterAll,
5
+ beforeAll,
6
+ beforeEach,
7
+ describe,
8
+ expect,
9
+ it,
10
+ } from "vitest";
11
+ import { initConfig } from "../config.js";
12
+ import { createMcpServer } from "../create-mcp-server.js";
13
+ import { handleReportIssue } from "../tools/report-issue.js";
14
+
15
+ /**
16
+ * Integration tests for the report_issue tool against a REAL local HTTP
17
+ * server. Corresponds to specs/mcp-server/report-issue-tool.feature.
18
+ */
19
+ describe("report_issue", () => {
20
+ let server: Server;
21
+ let endpoint: string;
22
+ let received: { headers: Record<string, unknown>; body: any }[];
23
+
24
+ beforeAll(async () => {
25
+ server = createServer((req, res) => {
26
+ let data = "";
27
+ req.on("data", (chunk: Buffer) => (data += chunk.toString()));
28
+ req.on("end", () => {
29
+ received.push({ headers: { ...req.headers }, body: JSON.parse(data) });
30
+ res.writeHead(201, { "content-type": "application/json" });
31
+ res.end(JSON.stringify({ id: "report-mcp-1" }));
32
+ });
33
+ });
34
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
35
+ endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
36
+ });
37
+
38
+ afterAll(async () => {
39
+ await new Promise((resolve) => server.close(resolve));
40
+ });
41
+
42
+ beforeEach(() => {
43
+ received = [];
44
+ initConfig({ endpoint, apiKey: undefined });
45
+ });
46
+
47
+ describe("given the registered tool set", () => {
48
+ /** @scenario "The report tool is listed with an agent-facing description" */
49
+ it("lists report_issue with the agent-facing consent description", () => {
50
+ const server = createMcpServer();
51
+ const tools = (
52
+ server as unknown as {
53
+ _registeredTools: Record<string, { description?: string }>;
54
+ }
55
+ )._registeredTools;
56
+ expect(Object.keys(tools)).toContain("report_issue");
57
+ const description = tools.report_issue?.description ?? "";
58
+ expect(description).toMatch(/whenever you struggled/i);
59
+ expect(description).toMatch(/ask the user for permission first/i);
60
+ });
61
+ });
62
+
63
+ describe("given the user did not approve sending", () => {
64
+ /** @scenario "Calls without user approval are rejected with instructions" */
65
+ it("refuses with instructions to ask the user first", async () => {
66
+ await expect(
67
+ handleReportIssue({
68
+ user_approved: false,
69
+ title: "broken tool",
70
+ summary: "search_traces 500s",
71
+ }),
72
+ ).rejects.toThrow(/ask the user/i);
73
+ expect(received).toHaveLength(0);
74
+ });
75
+ });
76
+
77
+ describe("given nothing to report", () => {
78
+ it("asks for a summary or session content", async () => {
79
+ await expect(
80
+ handleReportIssue({ user_approved: true, title: "empty" }),
81
+ ).rejects.toThrow(/Nothing to report/);
82
+ });
83
+ });
84
+
85
+ describe("when the user approved a summary report", () => {
86
+ /** @scenario "Reporting an issue through MCP reaches the LangWatch backend" */
87
+ it("delivers it marked as coming from MCP and returns a thank-you", async () => {
88
+ const text = await handleReportIssue({
89
+ user_approved: true,
90
+ title: "evaluator setup confusing",
91
+ summary: "the evaluator wizard 404s on step 2",
92
+ agent: "claude-code",
93
+ });
94
+
95
+ expect(received).toHaveLength(1);
96
+ expect(received[0]?.body.source).toBe("mcp");
97
+ expect(received[0]?.body.kind).toBe("summary");
98
+ expect(received[0]?.body.title).toBe("evaluator setup confusing");
99
+ expect(text).toContain("report-mcp-1");
100
+ expect(text.toLowerCase()).toContain("thank you");
101
+ });
102
+ });
103
+
104
+ describe("when the title itself includes a secret", () => {
105
+ it("redacts it before sending", async () => {
106
+ await handleReportIssue({
107
+ user_approved: true,
108
+ title: "X-Api-Key sk-proj-abcdefghijklmnopqrstuvwxyz123456 rejected",
109
+ summary: "the key was rejected",
110
+ });
111
+ expect(received[0]?.body.title).toBe("X-Api-Key [SECRET] rejected");
112
+ });
113
+ });
114
+
115
+ describe("when session content includes secrets", () => {
116
+ /** @scenario "Session content passed through MCP is redacted before sending" */
117
+ it("redacts them locally before sending", async () => {
118
+ await handleReportIssue({
119
+ user_approved: true,
120
+ title: "agent stuck",
121
+ session_content: JSON.stringify({
122
+ role: "user",
123
+ content: "my key sk-proj-abcdefghijklmnopqrstuvwxyz123456 failed",
124
+ }),
125
+ });
126
+
127
+ const wire = JSON.stringify(received[0]?.body);
128
+ expect(wire).not.toContain("sk-proj-abcdefghijklmnopqrstuvwxyz123456");
129
+ expect(received[0]?.body.sessionData).toContain("[SECRET]");
130
+ expect(received[0]?.body.kind).toBe("full_session");
131
+ });
132
+ });
133
+
134
+ describe("when an API key is configured", () => {
135
+ it("attaches it so the report links to the project", async () => {
136
+ initConfig({ endpoint, apiKey: "sk-lw-mcp-key-abcdef1234567890" });
137
+ await handleReportIssue({
138
+ user_approved: true,
139
+ title: "linked",
140
+ summary: "linked report",
141
+ });
142
+ expect(received[0]?.headers.authorization).toBe(
143
+ "Bearer sk-lw-mcp-key-abcdef1234567890",
144
+ );
145
+ });
146
+ });
147
+ });
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Shared fixtures for the standalone MCP HTTP server tests.
3
+ */
4
+
5
+ import { expect, vi } from "vitest";
6
+
7
+ import type { ApiKeyVerifier } from "../../http-security.js";
8
+ import { startHttpServer } from "../../http-server.js";
9
+
10
+ /** Standard headers the MCP Streamable HTTP protocol requires on POST. */
11
+ export const MCP_POST_HEADERS = {
12
+ "Content-Type": "application/json",
13
+ Accept: "application/json, text/event-stream",
14
+ };
15
+
16
+ export const VALID_KEY = "sk-lw-valid-key";
17
+ export const OTHER_VALID_KEY = "sk-lw-other-valid-key";
18
+
19
+ /**
20
+ * Stands in for the LangWatch API. The standalone server has no database, so
21
+ * it asks the API whether a key is real; here a fixed list is.
22
+ */
23
+ export function countingVerifier(validKeys: string[]) {
24
+ const verify = vi.fn(async (apiKey: string) => validKeys.includes(apiKey));
25
+ const verifier: ApiKeyVerifier = {
26
+ verify,
27
+ sweep: () => undefined,
28
+ clear: () => undefined,
29
+ };
30
+ return { verifier, verify };
31
+ }
32
+
33
+ /** A verifier whose accepted keys can change mid-test, to model revocation. */
34
+ export function revocableVerifier(initialKeys: string[]) {
35
+ const live = new Set(initialKeys);
36
+ const verifier: ApiKeyVerifier = {
37
+ verify: async (apiKey: string) => live.has(apiKey),
38
+ sweep: () => undefined,
39
+ clear: () => undefined,
40
+ };
41
+ return { verifier, revoke: (apiKey: string) => live.delete(apiKey) };
42
+ }
43
+
44
+ export interface Harness {
45
+ baseUrl: string;
46
+ close: () => Promise<void>;
47
+ }
48
+
49
+ export async function startHarness(
50
+ options: Parameters<typeof startHttpServer>[0]
51
+ ): Promise<Harness> {
52
+ const { server, port, host } = await startHttpServer(options);
53
+ return {
54
+ baseUrl: `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${port}`,
55
+ close: () =>
56
+ new Promise<void>((resolve) => {
57
+ server.close(() => resolve());
58
+ }),
59
+ };
60
+ }
61
+
62
+ export function initializeBody(): string {
63
+ return JSON.stringify({
64
+ jsonrpc: "2.0",
65
+ method: "initialize",
66
+ params: {
67
+ protocolVersion: "2025-03-26",
68
+ capabilities: {},
69
+ clientInfo: { name: "test-client", version: "1.0.0" },
70
+ },
71
+ id: 1,
72
+ });
73
+ }
74
+
75
+ export function toolsListBody(): string {
76
+ return JSON.stringify({ jsonrpc: "2.0", method: "tools/list", id: 2 });
77
+ }
78
+
79
+ /** Opens a Streamable HTTP session and returns its id. */
80
+ export async function openSession({
81
+ baseUrl,
82
+ apiKey = VALID_KEY,
83
+ }: {
84
+ baseUrl: string;
85
+ apiKey?: string;
86
+ }): Promise<string> {
87
+ const response = await fetch(`${baseUrl}/mcp`, {
88
+ method: "POST",
89
+ headers: { ...MCP_POST_HEADERS, Authorization: `Bearer ${apiKey}` },
90
+ body: initializeBody(),
91
+ });
92
+ expect(response.status).toBe(200);
93
+ await response.text();
94
+ return response.headers.get("mcp-session-id")!;
95
+ }
96
+
97
+ /**
98
+ * Reads an SSE stream until the endpoint event carrying the session id has
99
+ * arrived. A single read can return a partial frame, so waiting for the
100
+ * pattern rather than the first chunk keeps this from failing intermittently.
101
+ */
102
+ export async function readSessionId(response: Response): Promise<string> {
103
+ const reader = response.body!.getReader();
104
+ const decoder = new TextDecoder();
105
+ let buffered = "";
106
+
107
+ for (let reads = 0; reads < 20; reads++) {
108
+ const { value, done } = await reader.read();
109
+ if (done) break;
110
+ buffered += decoder.decode(value, { stream: true });
111
+ const match = /sessionId=([\w-]+)/.exec(buffered);
112
+ if (match?.[1]) return match[1];
113
+ }
114
+
115
+ throw new Error(`No session id in SSE stream. Received: ${buffered}`);
116
+ }
117
+
118
+ /**
119
+ * Sends `request` repeatedly until it answers 429, and returns that response
120
+ * along with how many attempts it took. Returns `rejected: undefined` when the
121
+ * limit never triggered within `maxAttempts`.
122
+ */
123
+ export async function requestUntilThrottled({
124
+ request,
125
+ maxAttempts = 30,
126
+ }: {
127
+ request: (attempt: number) => Promise<Response>;
128
+ maxAttempts?: number;
129
+ }): Promise<{ attempts: number; rejected: Response | undefined }> {
130
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
131
+ const response = await request(attempt);
132
+ if (response.status === 429) {
133
+ return { attempts: attempt + 1, rejected: response };
134
+ }
135
+ await response.text();
136
+ }
137
+ return { attempts: maxAttempts, rejected: undefined };
138
+ }
@@ -168,6 +168,30 @@ describe("handleSearchTraces()", () => {
168
168
  expect(result).toContain("timeout");
169
169
  });
170
170
 
171
+ describe("when a trace has evaluation results", () => {
172
+ it("shows pass/fail status per evaluation without requiring get_trace", async () => {
173
+ mockSearchTraces.mockResolvedValue({
174
+ traces: [
175
+ {
176
+ trace_id: "trace-eval",
177
+ input: { value: "" },
178
+ output: { value: "" },
179
+ evaluations: [
180
+ { name: "faithfulness", passed: true, score: 0.92 },
181
+ { evaluator_id: "toxicity-check", passed: false, label: "flagged" },
182
+ ],
183
+ },
184
+ ],
185
+ pagination: { totalHits: 1 },
186
+ });
187
+
188
+ const result = await handleSearchTraces({});
189
+
190
+ expect(result).toContain("**faithfulness**: PASSED (score: 0.92)");
191
+ expect(result).toContain("**toxicity-check**: FAILED [flagged]");
192
+ });
193
+ });
194
+
171
195
  describe("when no traces are found", () => {
172
196
  it("returns a no-results message", async () => {
173
197
  mockSearchTraces.mockResolvedValue({ traces: [] });
package/src/config.ts CHANGED
@@ -49,13 +49,28 @@ function getGlobalState(): McpGlobalState {
49
49
  };
50
50
  }
51
51
 
52
+ /**
53
+ * Trim surrounding whitespace and drop any trailing slashes.
54
+ *
55
+ * Request URLs are built as `${endpoint}/api/...`, so an endpoint written as
56
+ * `https://app.langwatch.ai/` would produce a double slash the router does not
57
+ * match, and the caller gets an opaque 404 with nothing pointing at the
58
+ * endpoint as the cause.
59
+ */
60
+ function normalizeEndpoint(endpoint: string): string {
61
+ const trimmed = endpoint.trim();
62
+ let end = trimmed.length;
63
+ while (end > 0 && trimmed[end - 1] === "/") end--;
64
+ return trimmed.slice(0, end);
65
+ }
66
+
52
67
  export function initConfig(args: { apiKey?: string; endpoint?: string }): void {
53
68
  const state = getGlobalState();
54
69
  state.globalConfig = {
55
70
  apiKey: args.apiKey || process.env.LANGWATCH_API_KEY,
56
71
  endpoint:
57
- args.endpoint ||
58
- process.env.LANGWATCH_ENDPOINT ||
72
+ normalizeEndpoint(args.endpoint ?? "") ||
73
+ normalizeEndpoint(process.env.LANGWATCH_ENDPOINT ?? "") ||
59
74
  "https://app.langwatch.ai",
60
75
  projectId: process.env.LANGWATCH_PROJECT_ID,
61
76
  };