@ttoss/http-server-mcp 0.33.2 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -37,7 +37,7 @@ var getApiHeaders = () => {
37
37
  /**
38
38
  * The `Accept-Language` header of the current MCP request, or `undefined`
39
39
  * outside a request or when the client sent none. The default locale source
40
- * for `createGatedToolRegistrar`'s `i18n` option.
40
+ * for `createToolGate`'s `i18n` option.
41
41
  */
42
42
  var getRequestLocale = () => {
43
43
  return requestContextStore.getStore()?.acceptLanguage;
@@ -364,24 +364,33 @@ var registerAppResource = ({
364
364
  };
365
365
 
366
366
  //#endregion
367
- //#region src/registerToolFromSchema.ts
367
+ //#region src/tool.ts
368
+ var EMPTY_OBJECT_SCHEMA = {
369
+ type: "object",
370
+ properties: {}
371
+ };
372
+ /** The JSON Schema dialect the MCP SDK converts Standard Schemas to. */
373
+ var JSON_SCHEMA_TARGET = "draft-2020-12";
374
+ var isStandardSchema = schema => {
375
+ return "~standard" in schema;
376
+ };
368
377
  /**
369
- * Converts a plain JSON Schema into the Standard Schema `registerTool` accepts.
378
+ * Converts a JSON Schema into the Standard Schema `registerTool` accepts.
370
379
  *
371
380
  * A Standard Schema keeps advertisement and enforcement in separate fields:
372
381
  * `~standard.jsonSchema` is what `tools/list` publishes, `~standard.validate`
373
382
  * is what `tools/call` runs. Replacing only `validate` therefore keeps the
374
383
  * schema fully visible to clients while leaving arguments unchecked.
375
384
  */
376
- var toStandardSchema = ({
377
- inputSchema,
378
- validateArguments
385
+ var fromJsonObjectSchema = ({
386
+ schema,
387
+ validate
379
388
  }) => {
380
- const schema = fromJsonSchema(inputSchema);
381
- if (validateArguments) return schema;
389
+ const standard = fromJsonSchema(schema);
390
+ if (validate) return standard;
382
391
  return {
383
392
  "~standard": {
384
- ...schema["~standard"],
393
+ ...standard["~standard"],
385
394
  validate: value => {
386
395
  return {
387
396
  value
@@ -390,71 +399,53 @@ var toStandardSchema = ({
390
399
  }
391
400
  };
392
401
  };
402
+ var resolved = /* @__PURE__ */new WeakMap();
393
403
  /**
394
- * Registers a tool on an MCP server using a **plain JSON Schema** object for
395
- * `inputSchema` instead of a Zod shape.
396
- *
397
- * This is useful when tool definitions are shared between the MCP server and
398
- * an AI SDK agent (e.g. Vercel AI SDK's `tool()` helper), because both consume
399
- * a plain JSON Schema at runtime. Using this helper eliminates the lossy
400
- * JSON-Schema→Zod conversion that would otherwise be required.
401
- *
402
- * Thin wrapper over `@modelcontextprotocol/server`'s `fromJsonSchema`, which
403
- * converts a JSON Schema into a Standard Schema that `registerTool` accepts
404
- * directly, so the schema round-trips verbatim over `tools/list`. Arguments
405
- * reach the handler unchecked unless `validateArguments` is enabled.
406
- *
407
- * @param server - The `McpServer` instance to register the tool on.
408
- * @param params - Tool configuration including name, description, inputSchema,
409
- * validateArguments, `_meta`, and handler.
410
- *
411
- * @example
412
- * ```typescript
413
- * import { registerToolFromSchema, McpServer } from '@ttoss/http-server-mcp';
414
- *
415
- * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
416
- *
417
- * registerToolFromSchema(server, {
418
- * name: 'get-project',
419
- * description: 'Get a project by ID',
420
- * inputSchema: {
421
- * type: 'object',
422
- * properties: { id: { type: 'string', description: 'Project public ID' } },
423
- * required: ['id'],
424
- * },
425
- * handler: async ({ id }) => ({
426
- * content: [{ type: 'text', text: `Project: ${id}` }],
427
- * }),
428
- * });
429
- * ```
404
+ * Resolves a tool's schemas once, so the direct registration and a deferred
405
+ * `call` enforce exactly the same thing.
430
406
  */
431
- var registerToolFromSchema = (server, params) => {
432
- const {
433
- name,
434
- description,
435
- inputSchema = {
436
- type: "object",
437
- properties: {}
438
- },
439
- validateArguments = false,
440
- handler,
441
- _meta
442
- } = params;
443
- server.registerTool(name, {
444
- description,
445
- inputSchema: toStandardSchema({
446
- inputSchema,
447
- validateArguments
407
+ var resolveToolSchemas = tool => {
408
+ const cached = resolved.get(tool);
409
+ if (cached) return cached;
410
+ const inputSchema = tool.inputSchema ?? EMPTY_OBJECT_SCHEMA;
411
+ const result = {
412
+ input: isStandardSchema(inputSchema) ? inputSchema : fromJsonObjectSchema({
413
+ schema: inputSchema,
414
+ validate: tool.validateArguments ?? false
448
415
  }),
449
- _meta
416
+ inputJson: isStandardSchema(inputSchema) ? inputSchema["~standard"].jsonSchema.input({
417
+ target: JSON_SCHEMA_TARGET
418
+ }) : inputSchema,
419
+ output: tool.outputSchema === void 0 || isStandardSchema(tool.outputSchema) ? tool.outputSchema : fromJsonObjectSchema({
420
+ schema: tool.outputSchema,
421
+ validate: true
422
+ })
423
+ };
424
+ resolved.set(tool, result);
425
+ return result;
426
+ };
427
+ /** Registers one tool as one MCP tool. */
428
+ var registerDirectTool = ({
429
+ server,
430
+ tool
431
+ }) => {
432
+ const schemas = resolveToolSchemas(tool);
433
+ server.registerTool(tool.name, {
434
+ title: tool.title,
435
+ description: tool.description,
436
+ inputSchema: schemas.input,
437
+ outputSchema: schemas.output,
438
+ annotations: tool.annotations,
439
+ _meta: tool._meta
450
440
  }, async args => {
451
- return handler(args);
441
+ return tool.handler(args);
452
442
  });
453
443
  };
454
-
455
- //#endregion
456
- //#region src/createGatedToolRegistrar.ts
457
- var toolError = (message, code) => {
444
+ /** An `isError` result whose text is `{ error, code? }` as JSON. */
445
+ var toolError = ({
446
+ message,
447
+ code
448
+ }) => {
458
449
  return {
459
450
  content: [{
460
451
  type: "text",
@@ -469,6 +460,591 @@ var toolError = (message, code) => {
469
460
  };
470
461
  };
471
462
  /**
463
+ * Builds a {@link Tool} from a `method` that returns data instead of a
464
+ * `CallToolResult`, which is what most hand-written tools want.
465
+ *
466
+ * @example
467
+ * ```typescript
468
+ * const getCampaign = defineTool({
469
+ * name: 'get-campaign',
470
+ * description: 'Get a campaign by id.',
471
+ * inputSchema: z.object({ campaignId: z.string() }),
472
+ * method: ({ campaignId }) => findCampaign(campaignId as string),
473
+ * notFoundMessage: 'Campaign not found',
474
+ * });
475
+ * ```
476
+ */
477
+ var defineTool = ({
478
+ method,
479
+ notFoundMessage = "Not found",
480
+ ...tool
481
+ }) => {
482
+ return {
483
+ ...tool,
484
+ handler: async args => {
485
+ const result = await method(args);
486
+ if (result == null) return toolError({
487
+ message: notFoundMessage
488
+ });
489
+ const content = [{
490
+ type: "text",
491
+ text: JSON.stringify(result)
492
+ }];
493
+ return tool.outputSchema === void 0 ? {
494
+ content
495
+ } : {
496
+ content,
497
+ structuredContent: result
498
+ };
499
+ }
500
+ };
501
+ };
502
+
503
+ //#endregion
504
+ //#region src/toolSearch.ts
505
+ var SUMMARY_MAX_LENGTH = 160;
506
+ var SUGGESTION_COUNT = 3;
507
+ var MIN_RELATED_SCORE = 1;
508
+ /** Plural and singular forms rank alike: `agents` finds `get-agent`. */
509
+ var stem = term => {
510
+ if (term.length > 4 && term.endsWith("ies")) return `${term.slice(0, -3)}y`;
511
+ if (term.length > 3 && term.endsWith("s") && !term.endsWith("ss")) return term.slice(0, -1);
512
+ return term;
513
+ };
514
+ /** Splits kebab-case, snake_case, camelCase and prose into lowercase terms. */
515
+ var termsOf = text => {
516
+ return text.replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, "$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(term => {
517
+ return term.length > 0;
518
+ }).map(stem);
519
+ };
520
+ /** The fields a query term is matched against, most telling first. */
521
+ var FIELDS = [{
522
+ weight: 4,
523
+ text: tool => {
524
+ return tool.name;
525
+ }
526
+ }, {
527
+ weight: 3,
528
+ text: tool => {
529
+ return tool.summary ?? "";
530
+ }
531
+ }, {
532
+ weight: 2,
533
+ text: tool => {
534
+ return (tool.tags ?? []).join(" ");
535
+ }
536
+ }, {
537
+ weight: 1,
538
+ text: tool => {
539
+ return tool.description;
540
+ }
541
+ }];
542
+ var fieldTerms = /* @__PURE__ */new WeakMap();
543
+ var termsByField = tool => {
544
+ const cached = fieldTerms.get(tool);
545
+ if (cached) return cached;
546
+ const terms = FIELDS.map(field => {
547
+ return new Set(termsOf(field.text(tool)));
548
+ });
549
+ fieldTerms.set(tool, terms);
550
+ return terms;
551
+ };
552
+ /**
553
+ * A term scores the weight of the best field holding it, half that when it
554
+ * is only a prefix of a word there (`proj` → `project`).
555
+ */
556
+ var scoreOf = ({
557
+ tool,
558
+ terms
559
+ }) => {
560
+ const fields = termsByField(tool);
561
+ let score = 0;
562
+ for (const term of terms) {
563
+ let best = 0;
564
+ for (const [index, words] of fields.entries()) {
565
+ const weight = FIELDS[index].weight;
566
+ if (words.has(term)) best = Math.max(best, weight);else if (term.length >= 3 && [...words].some(word => {
567
+ return word.startsWith(term);
568
+ })) best = Math.max(best, weight / 2);
569
+ }
570
+ score += best;
571
+ }
572
+ return score;
573
+ };
574
+ var withTag = ({
575
+ tag,
576
+ tools
577
+ }) => {
578
+ return tag === void 0 ? tools : tools.filter(tool => {
579
+ return tool.tags?.includes(tag) ?? false;
580
+ });
581
+ };
582
+ /**
583
+ * The tools `query` matches, best first, ties in the tools' order; `undefined`
584
+ * when the query has no words.
585
+ */
586
+ var scoreTools = ({
587
+ query,
588
+ tag,
589
+ tools
590
+ }) => {
591
+ const terms = [...new Set(termsOf(query))];
592
+ if (terms.length === 0) return void 0;
593
+ return withTag({
594
+ tag,
595
+ tools
596
+ }).map((tool, index) => {
597
+ return {
598
+ tool,
599
+ index,
600
+ score: scoreOf({
601
+ tool,
602
+ terms
603
+ })
604
+ };
605
+ }).filter(({
606
+ score
607
+ }) => {
608
+ return score > 0;
609
+ }).sort((a, b) => {
610
+ return b.score - a.score || a.index - b.index;
611
+ });
612
+ };
613
+ /**
614
+ * The deferred tools' default search: scores each tool by the query's terms,
615
+ * weighted name > summary > tags > description, and breaks ties by the
616
+ * tools' order. No index — a few hundred tools need none.
617
+ */
618
+ var rankTools = ({
619
+ query,
620
+ tag,
621
+ limit,
622
+ tools
623
+ }) => {
624
+ const scored = scoreTools({
625
+ query,
626
+ tag,
627
+ tools
628
+ });
629
+ if (!scored) return withTag({
630
+ tag,
631
+ tools
632
+ }).slice(0, limit);
633
+ return scored.slice(0, limit).map(({
634
+ tool
635
+ }) => {
636
+ return tool;
637
+ });
638
+ };
639
+ var summaryOf = tool => {
640
+ const [line] = (tool.summary ?? tool.description).trim().split("\n", 1);
641
+ return line.length > SUMMARY_MAX_LENGTH ? `${line.slice(0, SUMMARY_MAX_LENGTH - 1).trimEnd()}…` : line;
642
+ };
643
+ var editDistance = (a, b) => {
644
+ const row = Array.from({
645
+ length: b.length + 1
646
+ }, (_, index) => {
647
+ return index;
648
+ });
649
+ for (let i = 1; i <= a.length; i++) {
650
+ let diagonal = row[0];
651
+ row[0] = i;
652
+ for (let j = 1; j <= b.length; j++) {
653
+ const above = row[j];
654
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
655
+ diagonal = above;
656
+ }
657
+ }
658
+ return row[b.length];
659
+ };
660
+ /** Names a model probably meant: near-misses first, then related tools. */
661
+ var suggestionsFor = ({
662
+ name,
663
+ tools
664
+ }) => {
665
+ const tolerance = Math.max(2, Math.floor(name.length / 3));
666
+ const nearMisses = tools.map(tool => {
667
+ return {
668
+ name: tool.name,
669
+ distance: editDistance(name, tool.name)
670
+ };
671
+ }).filter(({
672
+ distance
673
+ }) => {
674
+ return distance <= tolerance;
675
+ }).sort((a, b) => {
676
+ return a.distance - b.distance;
677
+ }).map(candidate => {
678
+ return candidate.name;
679
+ });
680
+ const related = (scoreTools({
681
+ query: name,
682
+ tools
683
+ }) ?? []).filter(({
684
+ score
685
+ }) => {
686
+ return score >= MIN_RELATED_SCORE;
687
+ }).slice(0, SUGGESTION_COUNT).map(({
688
+ tool
689
+ }) => {
690
+ return tool.name;
691
+ });
692
+ return [...new Set([...nearMisses, ...related])].slice(0, SUGGESTION_COUNT);
693
+ };
694
+
695
+ //#endregion
696
+ //#region src/deferTools.ts
697
+ var DEFAULT_SEARCH_LIMIT = 10;
698
+ var DEFAULT_SEARCH_MAX_LIMIT = 50;
699
+ var jsonResult = ({
700
+ data,
701
+ isError = false
702
+ }) => {
703
+ return {
704
+ content: [{
705
+ type: "text",
706
+ text: JSON.stringify(data)
707
+ }],
708
+ structuredContent: data,
709
+ ...(isError ? {
710
+ isError: true
711
+ } : {})
712
+ };
713
+ };
714
+ var errorMessageOf = error => {
715
+ return error instanceof Error ? error.message : String(error);
716
+ };
717
+ var formatIssue = issue => {
718
+ const path = (issue.path ?? []).map(segment => {
719
+ return String(typeof segment === "object" ? segment.key : segment);
720
+ }).join(".");
721
+ return path ? `${path}: ${issue.message}` : issue.message;
722
+ };
723
+ var linksAppView = ({
724
+ tool
725
+ }) => {
726
+ const ui = tool._meta?.ui;
727
+ return typeof ui === "object" && ui !== null && "resourceUri" in ui || tool._meta?.["ui/resourceUri"] !== void 0;
728
+ };
729
+ var deferredToolsOf = ({
730
+ tools,
731
+ options
732
+ }) => {
733
+ const byName = /* @__PURE__ */new Map();
734
+ for (const tool of tools) {
735
+ if (byName.has(tool.name)) throw new Error(`Two tools are named "${tool.name}".`);
736
+ byName.set(tool.name, tool);
737
+ }
738
+ const isVisible = tool => {
739
+ return options.visible ? options.visible({
740
+ tool
741
+ }) : true;
742
+ };
743
+ const searchLimit = options.searchLimit ?? DEFAULT_SEARCH_LIMIT;
744
+ return {
745
+ names: {
746
+ search: "search",
747
+ describe: "describe",
748
+ call: "call",
749
+ ...options.names
750
+ },
751
+ tools,
752
+ searchLimit,
753
+ searchMaxLimit: options.searchMaxLimit ?? Math.max(DEFAULT_SEARCH_MAX_LIMIT, searchLimit),
754
+ searchTools: options.search ?? rankTools,
755
+ visibleTools: () => {
756
+ return tools.filter(isVisible);
757
+ },
758
+ find: name => {
759
+ const tool = byName.get(name);
760
+ return tool && isVisible(tool) ? tool : void 0;
761
+ }
762
+ };
763
+ };
764
+ var searchToolOf = ({
765
+ names,
766
+ tools,
767
+ searchLimit,
768
+ searchMaxLimit,
769
+ searchTools,
770
+ visibleTools
771
+ }) => {
772
+ const tags = [...new Set(tools.flatMap(tool => {
773
+ return tool.tags ?? [];
774
+ }))].sort();
775
+ return {
776
+ name: names.search,
777
+ description: `Find tools by keyword among the ${tools.length} this server offers. Returns each match's name and summary; get input schemas with "${names.describe}", then run one with "${names.call}".` + (tags.length > 0 ? ` Tags: ${tags.join(", ")}.` : ""),
778
+ inputSchema: {
779
+ type: "object",
780
+ properties: {
781
+ query: {
782
+ type: "string",
783
+ description: "Words describing the action, e.g. \"create agent\". Empty lists the tools in order."
784
+ },
785
+ tag: {
786
+ type: "string",
787
+ description: "Only tools with this tag.",
788
+ ...(tags.length > 0 ? {
789
+ enum: tags
790
+ } : {})
791
+ },
792
+ limit: {
793
+ type: "integer",
794
+ minimum: 1,
795
+ maximum: searchMaxLimit,
796
+ description: `Maximum number of results. Defaults to ${searchLimit}.`
797
+ }
798
+ },
799
+ required: ["query"]
800
+ },
801
+ validateArguments: true,
802
+ annotations: {
803
+ readOnlyHint: true
804
+ },
805
+ handler: async args => {
806
+ const limit = args.limit ?? searchLimit;
807
+ return jsonResult({
808
+ data: {
809
+ tools: (await searchTools({
810
+ query: args.query,
811
+ tag: args.tag,
812
+ limit,
813
+ tools: visibleTools()
814
+ })).slice(0, limit).map(tool => {
815
+ return {
816
+ name: tool.name,
817
+ summary: summaryOf(tool),
818
+ ...(tool.tags ? {
819
+ tags: tool.tags
820
+ } : {})
821
+ };
822
+ })
823
+ }
824
+ });
825
+ }
826
+ };
827
+ };
828
+ var describeToolOf = ({
829
+ names,
830
+ find,
831
+ visibleTools
832
+ }) => {
833
+ return {
834
+ name: names.describe,
835
+ description: `Get the full definition of tools found with "${names.search}", including the input schema "${names.call}" expects.`,
836
+ inputSchema: {
837
+ type: "object",
838
+ properties: {
839
+ names: {
840
+ type: "array",
841
+ items: {
842
+ type: "string"
843
+ },
844
+ minItems: 1,
845
+ description: "Tool names, as search returned them."
846
+ }
847
+ },
848
+ required: ["names"]
849
+ },
850
+ validateArguments: true,
851
+ annotations: {
852
+ readOnlyHint: true
853
+ },
854
+ handler: args => {
855
+ const described = [];
856
+ const unknown = [];
857
+ for (const name of args.names) {
858
+ const tool = find(name);
859
+ if (!tool) {
860
+ unknown.push({
861
+ name,
862
+ suggestions: suggestionsFor({
863
+ name,
864
+ tools: visibleTools()
865
+ })
866
+ });
867
+ continue;
868
+ }
869
+ described.push({
870
+ name: tool.name,
871
+ ...(tool.title ? {
872
+ title: tool.title
873
+ } : {}),
874
+ description: tool.description,
875
+ inputSchema: resolveToolSchemas(tool).inputJson,
876
+ ...(tool.annotations ? {
877
+ annotations: tool.annotations
878
+ } : {})
879
+ });
880
+ }
881
+ return jsonResult({
882
+ data: {
883
+ tools: described,
884
+ ...(unknown.length > 0 ? {
885
+ unknown
886
+ } : {})
887
+ },
888
+ isError: described.length === 0
889
+ });
890
+ }
891
+ };
892
+ };
893
+ /** Runs one tool the way a direct call would, with errors that help a retry. */
894
+ var runTool = async ({
895
+ tool,
896
+ args
897
+ }) => {
898
+ const schemas = resolveToolSchemas(tool);
899
+ const validated = await schemas.input["~standard"].validate(args);
900
+ if (validated.issues) return jsonResult({
901
+ data: {
902
+ error: `Invalid arguments for "${tool.name}".`,
903
+ issues: validated.issues.map(formatIssue),
904
+ inputSchema: schemas.inputJson
905
+ },
906
+ isError: true
907
+ });
908
+ const schemaHint = {
909
+ type: "text",
910
+ text: JSON.stringify({
911
+ inputSchema: schemas.inputJson
912
+ })
913
+ };
914
+ try {
915
+ const result = await tool.handler(validated.value);
916
+ return result.isError ? {
917
+ ...result,
918
+ content: [...result.content, schemaHint]
919
+ } : result;
920
+ } catch (error) {
921
+ return {
922
+ content: [{
923
+ type: "text",
924
+ text: errorMessageOf(error)
925
+ }, schemaHint],
926
+ isError: true
927
+ };
928
+ }
929
+ };
930
+ var callToolOf = ({
931
+ names,
932
+ find,
933
+ visibleTools
934
+ }) => {
935
+ return {
936
+ name: names.call,
937
+ description: `Run a tool found with "${names.search}". Pass its arguments as "${names.describe}" defined them.`,
938
+ inputSchema: {
939
+ type: "object",
940
+ properties: {
941
+ name: {
942
+ type: "string",
943
+ description: "The tool to run."
944
+ },
945
+ arguments: {
946
+ type: "object",
947
+ description: "The tool's arguments, matching its input schema."
948
+ }
949
+ },
950
+ required: ["name"]
951
+ },
952
+ validateArguments: true,
953
+ handler: args => {
954
+ const name = args.name;
955
+ const tool = find(name);
956
+ if (!tool) return jsonResult({
957
+ data: {
958
+ error: `Unknown tool "${name}".`,
959
+ suggestions: suggestionsFor({
960
+ name,
961
+ tools: visibleTools()
962
+ })
963
+ },
964
+ isError: true
965
+ });
966
+ return runTool({
967
+ tool,
968
+ args: args.arguments ?? {}
969
+ });
970
+ }
971
+ };
972
+ };
973
+ /**
974
+ * Defers `tools` behind three tools — `search`, `describe`, `call` — so a
975
+ * client's context holds three small definitions instead of every schema,
976
+ * and a schema enters it only for the tools the model is about to use.
977
+ */
978
+ var registerDeferredTools = ({
979
+ server,
980
+ tools,
981
+ ...options
982
+ }) => {
983
+ const deferred = deferredToolsOf({
984
+ tools,
985
+ options
986
+ });
987
+ for (const tool of [searchToolOf(deferred), describeToolOf(deferred), callToolOf(deferred)]) registerDirectTool({
988
+ server,
989
+ tool
990
+ });
991
+ const except = options.except ?? linksAppView;
992
+ for (const tool of tools) if (except({
993
+ tool
994
+ })) registerDirectTool({
995
+ server,
996
+ tool
997
+ });
998
+ };
999
+
1000
+ //#endregion
1001
+ //#region src/registerTools.ts
1002
+ /**
1003
+ * Registers tools on an MCP server, either one MCP tool each (the default)
1004
+ * or deferred behind `search` / `describe` / `call`. The same `tools` can feed
1005
+ * both, so two endpoints over one API cannot drift apart.
1006
+ *
1007
+ * @example
1008
+ * ```typescript
1009
+ * import { McpServer, registerTools, z } from '@ttoss/http-server-mcp';
1010
+ *
1011
+ * const tools = [
1012
+ * {
1013
+ * name: 'get-project',
1014
+ * description: 'Get a project by ID',
1015
+ * inputSchema: z.object({ id: z.string() }),
1016
+ * handler: async ({ id }) => ({
1017
+ * content: [{ type: 'text', text: `Project: ${id}` }],
1018
+ * }),
1019
+ * },
1020
+ * ];
1021
+ *
1022
+ * registerTools({ server: fullServer, tools });
1023
+ * registerTools({ server: deferredServer, tools, defer: true });
1024
+ * ```
1025
+ */
1026
+ var registerTools = ({
1027
+ server,
1028
+ tools,
1029
+ defer = false
1030
+ }) => {
1031
+ if (defer === false) {
1032
+ for (const tool of tools) registerDirectTool({
1033
+ server,
1034
+ tool
1035
+ });
1036
+ return;
1037
+ }
1038
+ registerDeferredTools({
1039
+ server,
1040
+ tools,
1041
+ ...(defer === true ? {} : defer)
1042
+ });
1043
+ };
1044
+
1045
+ //#endregion
1046
+ //#region src/toolGate.ts
1047
+ /**
472
1048
  * The localized `isError` result for `error`, or `undefined` when it is not
473
1049
  * a `LocalizedError` or rendering fails — the caller then keeps its usual path.
474
1050
  */
@@ -486,76 +1062,84 @@ var localizedToolError = async ({
486
1062
  error,
487
1063
  i18n: await i18n.catalog.getI18n(requested)
488
1064
  });
489
- return rendered ? toolError(rendered.message, rendered.code) : void 0;
1065
+ return rendered ? toolError({
1066
+ message: rendered.message,
1067
+ code: rendered.code
1068
+ }) : void 0;
490
1069
  } catch {
491
1070
  return;
492
1071
  }
493
1072
  };
494
1073
  /**
495
- * Factory that returns a `register` helper for MCP tools that require
496
- * authentication and a specific OAuth scope.
1074
+ * The package's `checkScopes` helper is not reused here because it throws
1075
+ * rather than returning an `isError` result, and it reads identity from
1076
+ * context itself.
1077
+ */
1078
+ var hasScope = ({
1079
+ identity,
1080
+ requiredScope
1081
+ }) => {
1082
+ return (Array.isArray(identity.scopes) ? identity.scopes : []).includes(requiredScope);
1083
+ };
1084
+ /**
1085
+ * Factory for a gate: a function that wraps a {@link Tool} so every call
1086
+ * passes the same authentication and authorization pipeline before its
1087
+ * handler runs. The gated tool is an ordinary `Tool`, so it registers
1088
+ * directly or joins a catalog like any other.
497
1089
  *
498
- * Every registered tool automatically:
1090
+ * Every gated call:
499
1091
  * 1. Resolves the caller identity (default: `getIdentity()`). Returns an
500
1092
  * `isError` result when the identity is absent (unauthenticated request).
501
1093
  * 2. When `enforceScope` is `true` (default), checks `requiredScope` — returns
502
1094
  * an `isError` result when the scope is absent, consistent with how MCP
503
- * surfaces authorization errors. The package's `checkScopes` helper is not
504
- * reused here because it throws rather than returning an `isError` result,
505
- * and it reads identity from context itself.
506
- * 3. Runs global `gates` then per-`register` `def.gates` in order; a throwing
507
- * gate rejects the call. Every gate receives the full {@link ToolCallContext}
508
- * (identity **and** the validated call args), enabling arg-conditional gates.
509
- * Gates own their own error handling; `onError` covers the tool handler only.
1095
+ * surfaces authorization errors.
1096
+ * 3. Runs global `gates` then the tool's `gates` in order; a throwing gate
1097
+ * rejects the call. Every gate receives the full {@link ToolCallContext}.
510
1098
  * 4. Merges `buildContext` output into the handler args.
511
- * 5. Wraps `null`/`undefined` results in a configurable "Not found" error result.
512
- * 6. Calls `onError` on handler throw before rethrowing.
513
- * 7. With `i18n`, renders a `LocalizedError` from a gate or the handler as an
1099
+ * 5. Calls `onError` on handler throw before rethrowing.
1100
+ * 6. With `i18n`, renders a `LocalizedError` from a gate or the handler as an
514
1101
  * `isError` result in the caller's locale instead of rethrowing it.
515
1102
  *
516
1103
  * @example
517
1104
  * ```typescript
518
- * const { register } = createGatedToolRegistrar({
519
- * server,
1105
+ * const gate = createToolGate({
520
1106
  * resolveIdentity: () => {
521
1107
  * const jwt = getIdentity<{ sub: string; scopes: string[] }>();
522
1108
  * return { userId: jwt!.sub, scopes: jwt!.scopes };
523
1109
  * },
524
1110
  * });
525
1111
  *
526
- * register({
527
- * name: 'activate-campaign',
528
- * description: 'Activate or deactivate a campaign.',
529
- * requiredScope: 'campaigns:write',
530
- * inputSchema: { isActive: z.boolean() },
531
- * // arg-conditional gate: active vs. inactive have different restrictions
532
- * gates: [
533
- * ({ args }) =>
534
- * args.isActive
535
- * ? subscriptionGate(['mustNotExceedMaxActive', 'mustHaveBudget'])
536
- * : subscriptionGate(['mustIncludeService']),
1112
+ * registerTools({
1113
+ * server,
1114
+ * tools: [
1115
+ * gate({
1116
+ * requiredScope: 'campaigns:write',
1117
+ * // arg-conditional gate: active vs. inactive have different restrictions
1118
+ * gates: [
1119
+ * ({ args }) =>
1120
+ * args.isActive
1121
+ * ? subscriptionGate(['mustNotExceedMaxActive', 'mustHaveBudget'])
1122
+ * : subscriptionGate(['mustIncludeService']),
1123
+ * ],
1124
+ * tool: defineTool({
1125
+ * name: 'activate-campaign',
1126
+ * description: 'Activate or deactivate a campaign.',
1127
+ * inputSchema: z.object({ isActive: z.boolean() }),
1128
+ * method: ({ userId, isActive }) => toggleCampaign(userId, isActive),
1129
+ * }),
1130
+ * }),
537
1131
  * ],
538
- * method: async ({ userId, isActive }) => toggleCampaign(userId, isActive),
539
1132
  * });
540
1133
  * ```
541
1134
  */
542
- var checkScope = (identity, requiredScope) => {
543
- if (!(Array.isArray(identity.scopes) ? identity.scopes : []).includes(requiredScope)) return toolError(`This tool requires the "${requiredScope}" scope.`);
544
- return null;
545
- };
546
- var runGates = async (allGates, ctx) => {
547
- for (const gate of allGates) await gate(ctx);
548
- };
549
- var createGatedToolRegistrar = ({
550
- server,
1135
+ var createToolGate = ({
551
1136
  resolveIdentity = getIdentity,
552
1137
  gates = [],
553
1138
  enforceScope = true,
554
1139
  onError,
555
1140
  buildContext,
556
- notFoundMessage = "Not found",
557
1141
  i18n
558
- }) => {
1142
+ } = {}) => {
559
1143
  const renderOrRethrow = async (error, ctx) => {
560
1144
  const localized = i18n ? await localizedToolError({
561
1145
  error,
@@ -565,60 +1149,46 @@ var createGatedToolRegistrar = ({
565
1149
  if (localized) return localized;
566
1150
  throw error;
567
1151
  };
568
- const runMethod = async (def, ctx) => {
569
- const extra = buildContext ? buildContext(ctx) : {};
570
- try {
571
- const result = await def.method({
572
- ...ctx.args,
573
- ...extra
574
- });
575
- if (result == null) return toolError(notFoundMessage);
576
- const content = [{
577
- type: "text",
578
- text: JSON.stringify(result)
579
- }];
580
- return def.outputSchema === void 0 ? {
581
- content
582
- } : {
583
- content,
584
- structuredContent: result
585
- };
586
- } catch (error) {
587
- if (onError) await onError(error, ctx);
588
- return renderOrRethrow(error, ctx);
589
- }
590
- };
591
- const register = def => {
592
- const handler = async args => {
593
- const identity = resolveIdentity();
594
- if (!identity) return toolError("Unauthorized");
595
- const ctx = {
596
- identity,
597
- args,
598
- handler: def.name
599
- };
600
- if (enforceScope) {
601
- const scopeError = checkScope(identity, def.requiredScope);
602
- if (scopeError) return scopeError;
603
- }
604
- try {
605
- await runGates([...gates, ...(def.gates ?? [])], ctx);
606
- } catch (error) {
607
- return renderOrRethrow(error, ctx);
1152
+ return ({
1153
+ tool,
1154
+ requiredScope,
1155
+ gates: toolGates = []
1156
+ }) => {
1157
+ return {
1158
+ ...tool,
1159
+ handler: async args => {
1160
+ const identity = resolveIdentity();
1161
+ if (!identity) return toolError({
1162
+ message: "Unauthorized"
1163
+ });
1164
+ const ctx = {
1165
+ identity,
1166
+ args,
1167
+ handler: tool.name
1168
+ };
1169
+ if (enforceScope && !hasScope({
1170
+ identity,
1171
+ requiredScope
1172
+ })) return toolError({
1173
+ message: `This tool requires the "${requiredScope}" scope.`
1174
+ });
1175
+ try {
1176
+ for (const gate of [...gates, ...toolGates]) await gate(ctx);
1177
+ } catch (error) {
1178
+ return renderOrRethrow(error, ctx);
1179
+ }
1180
+ const extra = buildContext ? buildContext(ctx) : {};
1181
+ try {
1182
+ return await tool.handler({
1183
+ ...args,
1184
+ ...extra
1185
+ });
1186
+ } catch (error) {
1187
+ if (onError) await onError(error, ctx);
1188
+ return renderOrRethrow(error, ctx);
1189
+ }
608
1190
  }
609
- return runMethod(def, ctx);
610
1191
  };
611
- server.registerTool(def.name, {
612
- title: def.title,
613
- description: def.description,
614
- inputSchema: def.inputSchema,
615
- outputSchema: def.outputSchema,
616
- annotations: def.annotations,
617
- _meta: def._meta
618
- }, handler);
619
- };
620
- return {
621
- register
622
1192
  };
623
1193
  };
624
1194
 
@@ -991,4 +1561,4 @@ var createMcpRouter = (server, options = {}) => {
991
1561
  };
992
1562
 
993
1563
  //#endregion
994
- export { InMemoryServerEventBus, McpServer, UI_EXTENSION_ID, UI_RESOURCE_MIME_TYPE, apiCall, checkScopes, createGatedToolRegistrar, createMcpRouter, errorBodyMessage, getApiHeaders, getIdentity, getRequestLocale, registerAppResource, registerToolFromSchema, z };
1564
+ export { InMemoryServerEventBus, McpServer, UI_EXTENSION_ID, UI_RESOURCE_MIME_TYPE, apiCall, checkScopes, createMcpRouter, createToolGate, defineTool, errorBodyMessage, getApiHeaders, getIdentity, getRequestLocale, rankTools, registerAppResource, registerTools, z };