@mastra/connect 1.3.2-alpha.3 → 1.4.0-alpha.5

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.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { tools } from './tools.js';
2
2
  export type { ToolsOptions, ToolsOptionsInput, ToolsProviderOptions, ToolsResolver, ToolsResolverContext, ToolsWithInput, } from './tools.js';
3
+ export type { CodeModeOptions, ConnectCodeMode } from './code-mode.js';
3
4
  export { channels } from './channels.js';
4
5
  export type { ChannelsOptions, ChannelsProviderOptions, ChannelsResolver, ChannelsResolverContext, ResolvedChannels, } from './channels.js';
5
6
  export type { ChannelProviderRegistration, ChannelInstance, ChannelRuntime } from './providers/channel-provider.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,YAAY,EACV,YAAY,EACZ,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,EACb,oBAAoB,EACpB,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,YAAY,EACV,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,2BAA2B,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACpH,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,YAAY,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AACrG,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,YAAY,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,mBAAmB,E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AM,aAAa,CAAC;AAC1D,YAAY,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACpD,YAAY,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { MCPClient } from "@mastra/mcp";
2
2
  import { z } from "zod";
3
3
  import { SpanType, resolveCurrentSpan } from "@mastra/core/observability";
4
- import { createTool } from "@mastra/core/tools";
4
+ import { createCodeMode, createCodeModeTool, createTool, generateStubs } from "@mastra/core/tools";
5
5
  import { hkdfSync } from "crypto";
6
6
  import { MASTRA_RESOURCE_ID_KEY } from "@mastra/core/request-context";
7
7
  // src/errors.ts
@@ -676,6 +676,174 @@ async function disconnectConnection(client, connectionId) {
676
676
  const response = await platformFetch(client, `/v2/connections/${encodeURIComponent(connectionId)}`, { method: "DELETE" });
677
677
  if (!response.ok) await throwPlatformError(response, `disconnecting connection ${connectionId}`);
678
678
  }
679
+ // src/function-search.ts
680
+ const SEARCH_TOOL_ID = "search_functions";
681
+ const DEFAULT_LIMIT = 8;
682
+ const MAX_LIMIT = 25;
683
+ /** Lowercase word list with a light plural strip, so "issues" finds `create_issue`. */
684
+ function words(text) {
685
+ return text.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).map((word) => word.length > 3 && word.endsWith("s") && !word.endsWith("ss") ? word.slice(0, -1) : word);
686
+ }
687
+ /**
688
+ * Ranks the program's functions for a query. Name words outweigh description
689
+ * words, rare words outweigh common ones (every Linear function says "linear"),
690
+ * and a query term that is a function's exact name always returns it.
691
+ */
692
+ function createSearch(tools, stubs) {
693
+ const descriptions = new Map(Object.values(tools).map((tool) => [tool.id, tool.description ?? ""]));
694
+ const entries = stubs.map((stub) => {
695
+ const name = new Set(words(stub.externalName));
696
+ return {
697
+ stub,
698
+ name,
699
+ text: /* @__PURE__ */ new Set([...name, ...words(descriptions.get(stub.toolId) ?? "")])
700
+ };
701
+ });
702
+ const frequency = /* @__PURE__ */ new Map();
703
+ for (const entry of entries) for (const word of entry.text) frequency.set(word, (frequency.get(word) ?? 0) + 1);
704
+ const weight = (word) => Math.log(1 + entries.length / (frequency.get(word) ?? entries.length));
705
+ const byName = new Map(entries.map((entry) => [entry.stub.externalName.toLowerCase(), entry]));
706
+ return (query, limit) => {
707
+ const exact = query.split(/\s+/).map((term) => byName.get(term.toLowerCase().replace(/^external_/, "").replace(/\(.*$/, ""))).filter((entry) => entry !== void 0);
708
+ const terms = [...new Set(words(query))];
709
+ const scored = entries.filter((entry) => !exact.includes(entry)).map((entry) => {
710
+ let score = 0;
711
+ for (const term of terms) if (entry.name.has(term)) score += 3 * weight(term);
712
+ else if (entry.text.has(term)) score += .5 * weight(term);
713
+ else if (term.length >= 4 && [...entry.name].some((word) => word.startsWith(term))) score += 2 * weight(term);
714
+ return {
715
+ entry,
716
+ score
717
+ };
718
+ }).filter(({ score }) => score > 0).sort((a, b) => b.score - a.score || a.entry.name.size - b.entry.name.size || a.entry.stub.externalName.localeCompare(b.entry.stub.externalName));
719
+ return [.../* @__PURE__ */ new Set([...exact, ...scored.map(({ entry }) => entry)])].slice(0, limit).map((entry) => entry.stub);
720
+ };
721
+ }
722
+ /** The `search_functions` tool: returns declarations for the functions that match a query. */
723
+ function createFunctionSearchTool(tools, stubs, codeToolId) {
724
+ const search = createSearch(tools, stubs);
725
+ return createTool({
726
+ id: SEARCH_TOOL_ID,
727
+ description: `Find the external_* functions a \`${codeToolId}\` program can call and get their TypeScript declarations. Search by what you need ("list linear teams") or by exact function names. Call this before writing a program that uses functions you have no declaration for.`,
728
+ inputSchema: z.object({
729
+ query: z.string().min(1).describe("What the functions should do, or exact function names separated by spaces."),
730
+ limit: z.number().int().min(1).max(MAX_LIMIT).optional().describe(`How many functions to return (default ${DEFAULT_LIMIT}).`)
731
+ }),
732
+ outputSchema: z.object({ declarations: z.string() }),
733
+ execute: async ({ query, limit }) => {
734
+ const found = search(query, limit ?? DEFAULT_LIMIT);
735
+ return { declarations: found.length ? found.map((stub) => stub.declaration).join("\n\n") : "No functions matched. Try other words, or exact names from the function list in your instructions." };
736
+ }
737
+ });
738
+ }
739
+ /** Code Mode instructions that list function names only; declarations come from `search_functions`. */
740
+ function searchModeInstructions(stubs, codeToolId) {
741
+ return `# Code Mode
742
+
743
+ You have access to the \`${codeToolId}\` tool. Instead of calling tools one at a time,
744
+ write a single TypeScript program that orchestrates them and returns one result.
745
+
746
+ There are too many functions to declare here, so only their names are listed
747
+ below, without their parameters. Work in two steps:
748
+ 1. Call the \`${SEARCH_TOOL_ID}\` tool directly (a regular tool call, not from inside a
749
+ program) with what you need, or with exact names from the list. It returns the
750
+ functions' TypeScript declarations.
751
+ 2. Call \`${codeToolId}\` with a program that only uses functions whose declarations
752
+ you have. Guessed parameters fail validation.
753
+
754
+ Rules:
755
+ - Call the available tools via the \`external_*\` functions. Each returns a
756
+ Promise — \`await\` it.
757
+ - Batch independent calls with \`Promise.all\`. Do arithmetic and data shaping in
758
+ JavaScript, not in your head.
759
+ - End the program by \`return\`-ing the final value (objects/arrays are fine).
760
+ - The only supported capabilities are the \`external_*\` functions. Do not rely
761
+ on filesystem, network, or process access — depending on the configured
762
+ sandbox and transport, the program may run fully isolated with none of those
763
+ available.
764
+ - Use \`console.log\` for debugging; logs are captured and returned.
765
+
766
+ Functions:
767
+ ${stubs.map((stub) => `external_${stub.externalName}`).join("\n")}`;
768
+ }
769
+ // src/code-mode.ts
770
+ /**
771
+ * How long one request reuses its build. An agent call resolves its
772
+ * instructions and tools separately; sharing one build keeps the declared
773
+ * functions identical to the ones the program can call. The window is short
774
+ * so a RequestContext reused across calls still picks up connection changes.
775
+ */
776
+ const REQUEST_BUILD_MS = 3e4;
777
+ /** Declarations above this size (about 10k tokens) switch to tool search unless `toolSearch` says otherwise. */
778
+ const SEARCH_THRESHOLD_CHARS = 4e4;
779
+ /**
780
+ * Tools that only work as direct agent tools: approval and suspension are
781
+ * handled by the agent loop, and a call from inside a program bypasses it. A
782
+ * per-call approval function counts too, since it cannot be decided up front.
783
+ */
784
+ function needsAgentLoop(tool) {
785
+ const candidate = tool;
786
+ return Boolean(candidate.requireApproval || candidate.needsApprovalFn || candidate.suspendSchema || candidate.resumeSchema);
787
+ }
788
+ function connectCodeMode(resolve, options = {}) {
789
+ const { transport, toolSearch, ...config } = options;
790
+ const builds = /* @__PURE__ */ new WeakMap();
791
+ const build = async (ctx) => {
792
+ const direct = {};
793
+ const orchestrated = {};
794
+ for (const [key, tool] of Object.entries(await resolve(ctx))) (needsAgentLoop(tool) ? direct : orchestrated)[key] = tool;
795
+ if (Object.keys(orchestrated).length === 0) return {
796
+ tools: direct,
797
+ instructions: ""
798
+ };
799
+ const stubs = generateStubs(orchestrated);
800
+ if (!(toolSearch ?? stubs.reduce((size, stub) => size + stub.declaration.length, 0) > SEARCH_THRESHOLD_CHARS)) {
801
+ const codeMode = createCodeMode({
802
+ ...config,
803
+ tools: orchestrated
804
+ }, transport);
805
+ return {
806
+ tools: {
807
+ ...direct,
808
+ [codeMode.tool.id]: codeMode.tool
809
+ },
810
+ instructions: codeMode.instructions
811
+ };
812
+ }
813
+ const codeTool = createCodeModeTool({
814
+ ...config,
815
+ tools: orchestrated
816
+ }, transport);
817
+ const searchTool = createFunctionSearchTool(orchestrated, stubs, codeTool.id);
818
+ return {
819
+ tools: {
820
+ ...direct,
821
+ [codeTool.id]: codeTool,
822
+ [searchTool.id]: searchTool
823
+ },
824
+ instructions: searchModeInstructions(stubs, codeTool.id)
825
+ };
826
+ };
827
+ const buildFor = (ctx) => {
828
+ const key = ctx?.requestContext;
829
+ if (typeof key !== "object" || key === null) return build(ctx);
830
+ const cached = builds.get(key);
831
+ if (cached && Date.now() - cached.startedAt < REQUEST_BUILD_MS) return cached.build;
832
+ const entry = {
833
+ build: build(ctx),
834
+ startedAt: Date.now()
835
+ };
836
+ builds.set(key, entry);
837
+ entry.build.catch(() => {
838
+ if (builds.get(key) === entry) builds.delete(key);
839
+ });
840
+ return entry.build;
841
+ };
842
+ return {
843
+ tools: async (ctx) => (await buildFor(ctx)).tools,
844
+ instructions: async (ctx) => (await buildFor(ctx)).instructions
845
+ };
846
+ }
679
847
  // src/connect-prompt-tool.ts
680
848
  /**
681
849
  * Record key of the built-in connect-prompt tool. Reserved: a provider tool
@@ -8133,11 +8301,15 @@ const SummarySchema = z.object({
8133
8301
  transcript_chapters: z.array(z.string()).nullish(),
8134
8302
  extended_sections: z.array(SummarySectionSchema).nullish()
8135
8303
  });
8136
- const ProviderSummarySchema$1 = SummarySchema.extend({ action_items: z.union([z.string(), z.array(z.string())]).nullish() });
8304
+ const ProviderSummarySchema$1 = SummarySchema.extend({
8305
+ action_items: z.union([z.string(), z.array(z.string())]).nullish(),
8306
+ keywords: z.union([z.string(), z.array(z.string())]).nullish()
8307
+ });
8137
8308
  const SpeakerSchema = z.object({
8138
8309
  id: z.string().nullish(),
8139
8310
  name: z.string().nullish()
8140
8311
  });
8312
+ const ProviderSpeakerSchema = SpeakerSchema.extend({ id: z.union([z.string(), z.number()]).nullish() });
8141
8313
  const MeetingInfoSchema = z.object({
8142
8314
  fred_joined: z.boolean().nullish(),
8143
8315
  silent_meeting: z.boolean().nullish(),
@@ -8183,7 +8355,7 @@ const TranscriptSchema = z.object({
8183
8355
  title: z.string().nullish(),
8184
8356
  sentences: z.array(ProviderSentenceSchema).nullish(),
8185
8357
  summary: ProviderSummarySchema$1.nullable().optional(),
8186
- speakers: z.array(SpeakerSchema).nullish(),
8358
+ speakers: z.array(ProviderSpeakerSchema).nullish(),
8187
8359
  meeting_info: MeetingInfoSchema.nullable().optional(),
8188
8360
  meeting_attendees: z.array(MeetingAttendeeSchema).nullish(),
8189
8361
  analytics: AnalyticsSchema.nullable().optional()
@@ -8209,6 +8381,15 @@ const getTranscriptOutputSchema = z.object({
8209
8381
  function normalizeActionItems$1(actionItems) {
8210
8382
  return Array.isArray(actionItems) ? actionItems.join("\n") : actionItems;
8211
8383
  }
8384
+ function normalizeKeywords(keywords) {
8385
+ return Array.isArray(keywords) ? keywords.join(", ") : keywords;
8386
+ }
8387
+ function normalizeSpeaker(speaker) {
8388
+ return {
8389
+ ...speaker,
8390
+ id: speaker.id != null ? String(speaker.id) : speaker.id
8391
+ };
8392
+ }
8212
8393
  function toFiniteNumber(value) {
8213
8394
  if (value == null) return void 0;
8214
8395
  if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
@@ -8333,9 +8514,10 @@ function getTranscriptTool(proxy) {
8333
8514
  sentences: transcript.sentences ? transcript.sentences.map(normalizeSentence) : void 0,
8334
8515
  summary: transcript.summary ? {
8335
8516
  ...transcript.summary,
8336
- action_items: transcript.summary.action_items != null ? normalizeActionItems$1(transcript.summary.action_items) : transcript.summary.action_items
8517
+ action_items: transcript.summary.action_items != null ? normalizeActionItems$1(transcript.summary.action_items) : transcript.summary.action_items,
8518
+ keywords: transcript.summary.keywords != null ? normalizeKeywords(transcript.summary.keywords) : transcript.summary.keywords
8337
8519
  } : void 0,
8338
- speakers: transcript.speakers ?? void 0,
8520
+ speakers: transcript.speakers ? transcript.speakers.map(normalizeSpeaker) : void 0,
8339
8521
  meeting_info: transcript.meeting_info ?? void 0,
8340
8522
  meeting_attendees: transcript.meeting_attendees ?? void 0,
8341
8523
  analytics: transcript.analytics ?? void 0
@@ -85884,7 +86066,8 @@ function tools(options = {}) {
85884
86066
  return refreshScope(state, acquireScope(state, staticResourceId));
85885
86067
  },
85886
86068
  disconnect: () => disconnectState(state),
85887
- with: (extra) => withExtraTools(resolver, extra)
86069
+ with: (extra) => withExtraTools(resolver, extra),
86070
+ codeMode: (codeModeOptions) => connectCodeMode(resolve, codeModeOptions)
85888
86071
  }));
85889
86072
  return resolver;
85890
86073
  }
@@ -85973,7 +86156,8 @@ function dynamicTools(getOptions) {
85973
86156
  })();
85974
86157
  return closing;
85975
86158
  },
85976
- with: (extra) => withExtraTools(resolver, extra)
86159
+ with: (extra) => withExtraTools(resolver, extra),
86160
+ codeMode: (codeModeOptions) => connectCodeMode(resolve, codeModeOptions)
85977
86161
  }));
85978
86162
  return resolver;
85979
86163
  }
@@ -86033,7 +86217,8 @@ function withExtraTools(base, extra) {
86033
86217
  };
86034
86218
  },
86035
86219
  disconnect: () => base.disconnect(),
86036
- with: (more) => withExtraTools(resolver, more)
86220
+ with: (more) => withExtraTools(resolver, more),
86221
+ codeMode: (codeModeOptions) => connectCodeMode(resolve, codeModeOptions)
86037
86222
  }));
86038
86223
  return resolver;
86039
86224
  }