Skip to content

Commit 908431e

Browse files
committed
feat: Add TracingContext type to various tools for enhanced tracing support
- Updated copywriter-agent-tool.ts to include TracingContext in the execute function. - Modified csv-to-json.tool.ts to utilize TracingContext in the execute function signature. - Enhanced data-file-manager.ts by adding TracingContext type to multiple execute functions. - Included TracingContext in the execute function of execa-tool.ts for better tracing. - Added TracingContext type to pdf-data-conversion.tool.ts for improved tracing capabilities. - Updated weather-tool.ts to incorporate TracingContext in the tool's context. - Enhanced web-scraper-tool.ts by adding TracingContext to the execute function across multiple tools. - Modified write-note.ts to include TracingContext in the execute function for better tracing.
1 parent 67f51af commit 908431e

8 files changed

Lines changed: 40 additions & 28 deletions

src/mastra/tools/copywriter-agent-tool.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { AISpanType, InternalSpans } from '@mastra/core/ai-tracing'
22
import { InferUITool, createTool } from "@mastra/core/tools";
33
import { z } from 'zod'
44
import { log } from '../config/logger'
5-
5+
import type { TracingContext } from '@mastra/core/ai-tracing';
66
// Define runtime context for this tool
77
export interface CopywriterToolContext {
88
userId?: string
@@ -70,7 +70,7 @@ export const copywriterTool = createTool({
7070
.optional()
7171
.describe('Approximate word count of the content'),
7272
}),
73-
execute: async ({ context, mastra, writer, tracingContext }) => {
73+
execute: async ({ context, mastra, writer, tracingContext } ) => {
7474
const {
7575
topic,
7676
contentType = 'blog',

src/mastra/tools/csv-to-json.tool.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { InferUITool, createTool } from "@mastra/core/tools";
33
import { parse } from "csv-parse/sync";
44
import * as fs from "node:fs/promises";
55
import { z } from "zod";
6+
import type { TracingContext } from '@mastra/core/ai-tracing';
67

78
const csvToolContextSchema = z.object({
89
maxRows: z.number().optional(),
@@ -33,7 +34,7 @@ export const csvToJsonTool = createTool({
3334
data: z.array(z.any()).describe("Parsed JSON data"),
3435
error: z.string().optional(),
3536
}),
36-
execute: async ({ context, writer, runtimeContext, tracingContext }) => {
37+
execute: async ({ context, writer, runtimeContext, tracingContext }: { context: { csvData?: string; filePath?: string; options?: { delimiter?: string; columns?: boolean; trim?: boolean; skip_empty_lines?: boolean } }, writer?: any, runtimeContext?: any, tracingContext?: TracingContext }) => {
3738
await writer?.write({ type: 'progress', data: { message: '📊 Starting CSV to JSON conversion' } });
3839
const rootSpan = tracingContext?.currentSpan?.createChildSpan({
3940
type: AISpanType.TOOL_CALL,
@@ -61,11 +62,18 @@ export const csvToJsonTool = createTool({
6162
throw new Error("Either csvData or filePath must be provided");
6263
}
6364

65+
const options = context.options ?? {
66+
delimiter: ",",
67+
columns: true,
68+
trim: true,
69+
skip_empty_lines: true,
70+
};
71+
6472
const records = parse(contentToParse, {
65-
delimiter: context.options.delimiter,
66-
columns: context.options.columns,
67-
trim: context.options.trim,
68-
skip_empty_lines: context.options.skip_empty_lines,
73+
delimiter: options.delimiter,
74+
columns: options.columns,
75+
trim: options.trim,
76+
skip_empty_lines: options.skip_empty_lines,
6977
});
7078

7179
if (maxRows !== undefined && records.length > maxRows) {

src/mastra/tools/data-file-manager.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { pipeline } from 'stream/promises'
2121
import * as zlib from 'zlib'
2222
import { z } from 'zod'
2323
import { log } from '../config/logger'
24+
import type { TracingContext } from '@mastra/core/ai-tracing';
2425

2526
// Define runtime context for these tools
2627
export interface DataFileManagerContext {
@@ -58,7 +59,7 @@ export const readDataFileTool = createTool({
5859
),
5960
}),
6061
outputSchema: z.string().describe('The content of the file as a string.'),
61-
execute: async ({ context, writer, tracingContext }) => {
62+
execute: async ({ context, writer, tracingContext }: { context: { fileName: string }, writer?: any, tracingContext?: TracingContext }) => {
6263
await writer?.write({ type: 'progress', data: { message: '📖 Reading file: ' + context.fileName } });
6364
const readSpan = tracingContext?.currentSpan?.createChildSpan({
6465
type: AISpanType.TOOL_CALL,
@@ -108,7 +109,7 @@ export const writeDataFileTool = createTool({
108109
outputSchema: z
109110
.string()
110111
.describe('A confirmation string indicating success.'),
111-
execute: async ({ context, writer, tracingContext }) => {
112+
execute: async ({ context, writer, tracingContext }: { context: { fileName: string, content: string }, writer?: any, tracingContext?: TracingContext }) => {
112113
await writer?.write({ type: 'progress', data: { message: '💾 Writing to file: ' + context.fileName } });
113114
const writeSpan = tracingContext?.currentSpan?.createChildSpan({
114115
type: AISpanType.TOOL_CALL,
@@ -167,7 +168,7 @@ export const deleteDataFileTool = createTool({
167168
outputSchema: z
168169
.string()
169170
.describe('A confirmation string indicating success.'),
170-
execute: async ({ context, writer, tracingContext }) => {
171+
execute: async ({ context, writer, tracingContext }: { context: { fileName: string }, writer?: any, tracingContext?: TracingContext }) => {
171172
await writer?.write({ type: 'progress', data: { message: '🗑️ Deleting file: ' + context.fileName } });
172173
const deleteSpan = tracingContext?.currentSpan?.createChildSpan({
173174
type: AISpanType.TOOL_CALL,
@@ -216,7 +217,7 @@ export const listDataDirTool = createTool({
216217
outputSchema: z
217218
.array(z.string())
218219
.describe('An array of file and directory names.'),
219-
execute: async ({ context, writer, tracingContext }) => {
220+
execute: async ({ context, writer, tracingContext }: { context: { dirPath?: string }, writer?: any, tracingContext?: TracingContext }) => {
220221
await writer?.write({ type: 'progress', data: { message: '📂 Listing directory: ' + (context.dirPath ?? 'docs/data') } });
221222
const listSpan = tracingContext?.currentSpan?.createChildSpan({
222223
type: AISpanType.TOOL_CALL,
@@ -268,7 +269,7 @@ export const copyDataFileTool = createTool({
268269
outputSchema: z
269270
.string()
270271
.describe('A confirmation string indicating success.'),
271-
execute: async ({ context, writer, tracingContext }) => {
272+
execute: async ({ context, writer, tracingContext }: { context: { sourceFile: string, destFile: string }, writer?: any, tracingContext?: TracingContext }) => {
272273
await writer?.write({ type: 'progress', data: { message: `📋 Copying file: ${context.sourceFile} to ${context.destFile}` } });
273274
const copySpan = tracingContext?.currentSpan?.createChildSpan({
274275
type: AISpanType.TOOL_CALL,
@@ -329,7 +330,7 @@ export const moveDataFileTool = createTool({
329330
outputSchema: z
330331
.string()
331332
.describe('A confirmation string indicating success.'),
332-
execute: async ({ context, writer, tracingContext }) => {
333+
execute: async ({ context, writer, tracingContext }: { context: { sourceFile: string, destFile: string }, writer?: any, tracingContext?: TracingContext }) => {
333334
await writer?.write({ type: 'progress', data: { message: `🚚 Moving file: ${context.sourceFile} to ${context.destFile}` } });
334335
const moveSpan = tracingContext?.currentSpan?.createChildSpan({
335336
type: AISpanType.TOOL_CALL,
@@ -396,7 +397,7 @@ export const searchDataFilesTool = createTool({
396397
outputSchema: z
397398
.array(z.string())
398399
.describe('An array of matching file paths.'),
399-
execute: async ({ context, writer, tracingContext }) => {
400+
execute: async ({ context, writer, tracingContext }: { context: { pattern: string, searchContent?: boolean, dirPath?: string }, writer?: any, tracingContext?: TracingContext }) => {
400401
await writer?.write({ type: 'progress', data: { message: `🔍 Searching for pattern: "${context.pattern}"` } });
401402
const searchSpan = tracingContext?.currentSpan?.createChildSpan({
402403
type: AISpanType.TOOL_CALL,
@@ -498,7 +499,7 @@ export const getDataFileInfoTool = createTool({
498499
isDirectory: z.boolean(),
499500
})
500501
.describe('File metadata information.'),
501-
execute: async ({ context, writer, tracingContext }) => {
502+
execute: async ({ context, writer, tracingContext }: { context: { fileName: string }, writer?: any, tracingContext?: TracingContext }) => {
502503
await writer?.write({ type: 'progress', data: { message: 'ℹ️ Getting info for file: ' + context.fileName } });
503504
const infoSpan = tracingContext?.currentSpan?.createChildSpan({
504505
type: AISpanType.TOOL_CALL,

src/mastra/tools/execa-tool.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { execa, ExecaError } from 'execa';
55
import { Transform } from 'stream';
66
import { z } from 'zod';
77
import { log } from '../config/logger';
8-
8+
import type { TracingContext } from '@mastra/core/ai-tracing';
99
// Create transform stream that applies chalk
1010
const colorTransform = new Transform({
1111
transform(chunk, _encoding, callback) {
@@ -27,7 +27,7 @@ export const execaTool = createTool({
2727
message: z.string(),
2828
}),
2929

30-
execute: async ({ context, writer, tracingContext }) => {
30+
execute: async ({ context, writer, tracingContext }: { context: { command: string; args: string[] }, writer?: any, tracingContext?: TracingContext }) => {
3131
const span = tracingContext?.currentSpan?.createChildSpan({
3232
type: AISpanType.TOOL_CALL,
3333
name: 'execa-tool',

src/mastra/tools/pdf-data-conversion.tool.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { context } from '@opentelemetry/api';
12
// Kilocode: Tool Approval
23
// owner: team-data
34
// justification: PDF parsing and markdown conversion for RAG indexing
@@ -25,6 +26,7 @@ import {
2526
logError,
2627
logToolExecution,
2728
} from '../config/logger'
29+
import type { TracingContext } from '@mastra/core/ai-tracing';
2830

2931
// Lazy-loaded pdf-parse to avoid demo parsing errors
3032
let pdfParse: unknown = null
@@ -498,7 +500,7 @@ Perfect for RAG indexing, documentation conversion, and content processing.
498500
`,
499501
inputSchema: PdfToMarkdownInputSchema,
500502
outputSchema: PdfToMarkdownOutputSchema,
501-
execute: async ({ context, tracingContext, writer }) => {
503+
execute: async ({ context, tracingContext, writer } ) => {
502504
const startTime = Date.now()
503505
logToolExecution('pdf-to-markdown', { input: context })
504506

src/mastra/tools/weather-tool.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { z } from 'zod'
33
import { log } from '../config/logger'
44
import { AISpanType, InternalSpans } from '@mastra/core/ai-tracing'
55
import { RuntimeContext } from '@mastra/core/runtime-context'
6+
import type { TracingContext } from '@mastra/core/ai-tracing';
67

78
// Define the Zod schema for the runtime context
89
const weatherToolContextSchema = z.object({

src/mastra/tools/web-scraper-tool.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import * as fs from 'node:fs/promises'
2424
import * as path from 'node:path'
2525
import { JSDOM } from 'jsdom'
2626
import { log } from '../config/logger'
27-
27+
import type { TracingContext } from '@mastra/core/ai-tracing';
2828
// Enhanced HTML processing with JSDOM
2929
const DANGEROUS_TAGS = new Set([
3030
'script',
@@ -408,7 +408,7 @@ export const webScraperTool = createTool({
408408
'Extracts structured data from web pages using JSDOM and Cheerio with enhanced security and error handling.',
409409
inputSchema: webScraperInputSchema,
410410
outputSchema: webScraperOutputSchema,
411-
execute: async ({ context, writer, tracingContext }) => {
411+
execute: async ({ context, writer, tracingContext }: { context: { url: string; selector?: string; extractAttributes?: string[]; saveMarkdown?: boolean; markdownFileName?: string }, writer?: any, tracingContext?: TracingContext }) => {
412412
await writer?.write({ type: 'progress', data: { message: `🌐 Starting web scrape for ${context.url}` } });
413413
toolCallCounters.set('web-scraper', (toolCallCounters.get('web-scraper') ?? 0) + 1)
414414
const scrapeSpan = tracingContext?.currentSpan?.createChildSpan({
@@ -741,7 +741,7 @@ export const batchWebScraperTool = createTool({
741741
'Scrape multiple web pages concurrently with enhanced JSDOM processing and rate limiting.',
742742
inputSchema: batchWebScraperInputSchema,
743743
outputSchema: batchWebScraperOutputSchema,
744-
execute: async ({ context, writer, tracingContext }) => {
744+
execute: async ({ context, writer, tracingContext }: { context: { urls: string[]; selector?: string; maxConcurrent?: number; saveResults?: boolean; baseFileName?: string }, writer?: any, tracingContext?: TracingContext }) => {
745745
await writer?.write({ type: 'progress', data: { message: `🌐 Batch scraping ${context.urls.length} URLs` } });
746746
toolCallCounters.set('batch-web-scraper', (toolCallCounters.get('batch-web-scraper') ?? 0) + 1)
747747
const batchSpan = tracingContext?.currentSpan?.createChildSpan({
@@ -1000,7 +1000,7 @@ export const siteMapExtractorTool = createTool({
10001000
'Extract a comprehensive site map by crawling internal links with enhanced JSDOM processing and rate limiting.',
10011001
inputSchema: siteMapExtractorInputSchema,
10021002
outputSchema: siteMapExtractorOutputSchema,
1003-
execute: async ({ context, writer, tracingContext }) => {
1003+
execute: async ({ context, writer, tracingContext }: { context: { url: string; maxDepth?: number; maxPages?: number; includeExternal?: boolean; saveMap?: boolean }, writer?: any, tracingContext?: TracingContext }) => {
10041004
await writer?.write({ type: 'progress', data: { message: `🗺️ Starting site map extraction for ${context.url}` } });
10051005
toolCallCounters.set('site-map-extractor', (toolCallCounters.get('site-map-extractor') ?? 0) + 1)
10061006
const mapSpan = tracingContext?.currentSpan?.createChildSpan({
@@ -1259,7 +1259,7 @@ export const linkExtractorTool = createTool({
12591259
'Extract and analyze all links from a web page with enhanced JSDOM processing and filtering.',
12601260
inputSchema: linkExtractorInputSchema,
12611261
outputSchema: linkExtractorOutputSchema,
1262-
execute: async ({ context, writer, tracingContext }) => {
1262+
execute: async ({ context, writer, tracingContext }: { context: { url: string; linkTypes?: ('internal' | 'external' | 'all')[]; includeAnchors?: boolean; filterPatterns?: string[] }, writer?: any, tracingContext?: TracingContext }) => {
12631263
await writer?.write({ type: 'progress', data: { message: `🔗 Extracting links from ${context.url}` } });
12641264
toolCallCounters.set('link-extractor', (toolCallCounters.get('link-extractor') ?? 0) + 1)
12651265
const linkSpan = tracingContext?.currentSpan?.createChildSpan({
@@ -1489,7 +1489,7 @@ export const htmlToMarkdownTool = createTool({
14891489
'Convert HTML content to well-formatted markdown with enhanced JSDOM parsing and security.',
14901490
inputSchema: htmlToMarkdownInputSchema,
14911491
outputSchema: htmlToMarkdownOutputSchema,
1492-
execute: async ({ context, writer, tracingContext }) => {
1492+
execute: async ({ context, writer, tracingContext }: { context: { html: string; saveToFile?: boolean; fileName?: string }, writer?: any, tracingContext?: TracingContext }) => {
14931493
await writer?.write({ type: 'progress', data: { message: '🔄 Converting HTML to markdown...' } });
14941494
toolCallCounters.set('html-to-markdown', (toolCallCounters.get('html-to-markdown') ?? 0) + 1)
14951495
const convertSpan = tracingContext?.currentSpan?.createChildSpan({
@@ -1621,7 +1621,7 @@ export const listScrapedContentTool = createTool({
16211621
'List all scraped content files stored in the data directory with enhanced security.',
16221622
inputSchema: listScrapedContentInputSchema,
16231623
outputSchema: listScrapedContentOutputSchema,
1624-
execute: async ({ context, writer, tracingContext }) => {
1624+
execute: async ({ context, writer, tracingContext }: { context: { pattern?: string; includeMetadata?: boolean }, writer?: any, tracingContext?: TracingContext }) => {
16251625
await writer?.write({ type: 'progress', data: { message: '📂 Listing scraped content files...' } });
16261626
toolCallCounters.set('list-scraped-content', (toolCallCounters.get('list-scraped-content') ?? 0) + 1)
16271627
const listSpan = tracingContext?.currentSpan?.createChildSpan({
@@ -1812,7 +1812,7 @@ export const contentCleanerTool = createTool({
18121812
'Clean HTML content by removing unwanted elements with enhanced JSDOM processing and security.',
18131813
inputSchema: contentCleanerInputSchema,
18141814
outputSchema: contentCleanerOutputSchema,
1815-
execute: async ({ context, writer, tracingContext }) => {
1815+
execute: async ({ context, writer, tracingContext }: { context: { html: string; removeScripts?: boolean; removeStyles?: boolean; removeComments?: boolean; preserveStructure?: boolean }, writer?: any, tracingContext?: TracingContext }) => {
18161816
await writer?.write({ type: 'progress', data: { message: '🧹 Starting content cleaning...' } });
18171817
toolCallCounters.set('content-cleaner', (toolCallCounters.get('content-cleaner') ?? 0) + 1)
18181818
const cleanSpan = tracingContext?.currentSpan?.createChildSpan({

src/mastra/tools/write-note.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { AISpanType } from "@mastra/core/ai-tracing";
33
import { z } from "zod";
44
import path from "node:path";
55
import fs from "fs/promises";
6-
6+
import type { TracingContext } from '@mastra/core/ai-tracing';
77

88
const NOTES_DIR = path.join(process.cwd(), "notes");
99

@@ -21,7 +21,7 @@ export const writeNoteTool = createTool({
2121
.describe("The markdown content of the note."),
2222
}),
2323
outputSchema: z.string().nonempty(),
24-
execute: async ({ context, tracingContext }) => {
24+
execute: async ({ context, tracingContext }: { context: { title: string; content: string }, tracingContext?: TracingContext }) => {
2525
const startTime = Date.now();
2626
const span = tracingContext?.currentSpan?.createChildSpan({
2727
type: AISpanType.TOOL_CALL,

0 commit comments

Comments
 (0)