Skip to content

feat: v1 Mastra migration#29

Merged
ssdeanx merged 1 commit intomainfrom
develop
Dec 10, 2025
Merged

feat: v1 Mastra migration#29
ssdeanx merged 1 commit intomainfrom
develop

Conversation

@ssdeanx
Copy link
Owner

@ssdeanx ssdeanx commented Dec 10, 2025

  • Implemented AuthenticationService for JWT verification and access policy generation.
  • Introduced DocumentIndexingService for processing and indexing documents with enhanced chunking and embedding capabilities.
  • Added support for security tag extraction based on document classification and allowed roles.

feat: Introduce A2A and ACP AI providers

  • Created a2a.ts to demonstrate integration with A2A AI provider for streaming text responses.
  • Developed acp.ts to set up the Gemini ACP provider with necessary configurations.

feat: Define agent schemas using Zod

  • Established comprehensive schemas for various agents including JWT claims, access filters, document contexts, and output formats.
  • Included validation for subscription tiers, usage stats, and content generation workflows.

docs: Add initial API documentation for Mastra v1

  • Created v1.md to provide guidance on migration and usage of the new API features.

- Implemented AuthenticationService for JWT verification and access policy generation.
- Introduced DocumentIndexingService for processing and indexing documents with enhanced chunking and embedding capabilities.
- Added support for security tag extraction based on document classification and allowed roles.

feat: Introduce A2A and ACP AI providers
- Created a2a.ts to demonstrate integration with A2A AI provider for streaming text responses.
- Developed acp.ts to set up the Gemini ACP provider with necessary configurations.

feat: Define agent schemas using Zod
- Established comprehensive schemas for various agents including JWT claims, access filters, document contexts, and output formats.
- Included validation for subscription tiers, usage stats, and content generation workflows.

docs: Add initial API documentation for Mastra v1
- Created v1.md to provide guidance on migration and usage of the new API features.
Copilot AI review requested due to automatic review settings December 10, 2025 15:37
@continue
Copy link

continue bot commented Dec 10, 2025

Keep this PR in a mergeable state →

Learn more

All Green is an AI agent that automatically:

✅ Addresses code review comments

✅ Fixes failing CI checks

✅ Resolves merge conflicts

@greptile-apps
Copy link

greptile-apps bot commented Dec 10, 2025

Skipped: This PR changes more files than the configured file change limit: (136 files found, 100 file limit)

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, we are unable to review this pull request

The GitHub API does not allow us to fetch diffs exceeding 20000 lines

@github-actions
Copy link

🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@coderabbitai
Copy link

coderabbitai bot commented Dec 10, 2025

Caution

Review failed

The pull request is closed.

Summary by CodeRabbit

Release Notes

  • Documentation

    • Added comprehensive v1 migration guide covering tools, tracing, and observability updates
    • Added v1 API documentation and guides
    • Expanded custom metadata and observability documentation with configuration examples
  • New Features

    • Added bundle analyzer integration for Next.js builds
    • Introduced new authentication and document indexing services
    • Added comprehensive agent schema definitions for standardized inputs and outputs
  • Chores

    • Upgraded core dependencies to v1 beta releases
    • Updated environment configuration with bundle analyzer support
    • Modernized observability integration and tracing infrastructure

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Comprehensive v1 migration refactoring RuntimeContext to RequestContext throughout agents, tools, and APIs, migrating custom AISpan tracing to OpenTelemetry, standardizing tool execute signatures to (inputData, context), upgrading core Mastra dependencies from 0.x to 1.x beta, adding scorer identifiers and prebuilt scorers, and introducing new authentication and document indexing services.

Changes

Cohort / File(s) Change Summary
Agent Configuration Migration
src/mastra/agents/* (acpAgent.ts, businessLegalAgents.ts, calendarAgent.ts, codingAgents.ts, contentStrategistAgent.ts, copywriterAgent.ts, csv_to_excalidraw.ts, dane.ts, dataExportAgent.ts, dataIngestionAgent.ts, dataTransformationAgent.ts, documentProcessingAgent.ts, editorAgent.ts, evaluationAgent.ts, excalidraw_validator.ts, image.ts, image_to_csv.ts, knowledgeIndexingAgent.ts, learningExtractionAgent.ts, package-publisher.ts, recharts.ts, reportAgent.ts, researchAgent.ts, researchPaperAgent.ts, scriptWriterAgent.ts, sql.ts, stockAnalysisAgent.ts, weather-agent.ts)
Replaced RuntimeContext with RequestContext in all instruction/model handlers; removed InternalSpans tracing policy configurations; updated scorer imports from @mastra/evals/scorers/llm to @mastra/evals/scorers/prebuilt; added explicit sampling configurations to several agents.
A2A Coordinator Updates
src/mastra/a2a/a2aCoordinatorAgent.ts, src/mastra/a2a/codingA2ACoordinator.ts
Migrated from RuntimeContext to RequestContext; updated scorer imports to prebuilt; removed tracing policy configurations; enhanced system instructions.
Tool Execute Signature Refactor
src/mastra/tools/* (alpha-vantage.tool.ts, arxiv.tool.ts, browser-tool.ts, calendar-tool.ts, code-analysis.tool.ts, code-search.tool.ts, copywriter-agent-tool.ts, csv-to-json.tool.ts, data-file-manager.ts, data-processing-tools.ts, data-validator.tool.ts, diff-review.tool.ts, document-chunking.tool.ts, editor-agent-tool.ts, evaluateResultTool.ts, execa-tool.ts, extractLearningsTool.ts, financial-chart-tools.ts, find-references.tool.ts, find-symbol.tool.ts, finnhub-tools.ts, fs.ts, github.ts, json-to-csv.tool.ts, jwt-auth.tool.ts, multi-string-edit.tool.ts, pdf-data-conversion.tool.ts, pdf.ts, pg-sql-tool.ts, pnpm-tool.ts, polygon-tools.ts)
Unified tool execute signatures from destructured context patterns to (inputData, context) form; replaced OpenTelemetry AISpan tracing with direct OpenTelemetry API via trace.getTracer(); replaced writer.write() with context.writer.custom() for progress signaling; updated error handling with span.recordException() and span.setStatus().
Tracing System Overhaul
instrumentation.ts, src/mastra/config/mongodb.ts, src/mastra/config/pg-storage.ts, src/mastra/index.ts
Migrated from custom AISpan-based spans to OpenTelemetry API tracing; updated imports to use @mastra/observability instead of @mastra/core/ai-tracing; removed deprecated telemetry blocks and default exporters; introduced Observability class with spanOutputProcessors and SensitiveDataFilter.
Storage & Memory Configuration
src/mastra/config/mongodb.ts, src/mastra/config/pg-storage.ts, src/mastra/config/upstash.ts, src/mastra/config/vector/*, src/mastra/mcp/server.ts
Added explicit id parameters to storage/vector instances (pg:store, pg:vector, mongo:store, mongo:vector, upstash:store, upstash:vector, qdrant:store, mcp:notes); refactored tracing in pg-storage.ts to use OpenTelemetry; removed TokenLimiter from pgMemory.
Scorer Updates
src/mastra/scorers/* (csv-validity.scorer.ts, custom-scorers.ts, factuality.scorer.ts, financial-scorers.ts, script-scorers.ts, sql-validity.scorer.ts, structure.scorer.ts, tone-consistency.scorer.ts, weather-scorer.ts)
Added mandatory id field to all scorer exports; updated imports from @mastra/core/scores to @mastra/core/evals; added runEvals imports; refined JSON parsing and condition handling; introduced ContextType for structure scorer.
Network Configuration
src/mastra/networks/* (codingTeamNetwork.ts, dataPipelineNetwork.ts, index.ts, reportGenerationNetwork.ts, researchPipelineNetwork.ts)
Removed InternalSpans import and tracing policy configurations; simplified to empty options objects.
New Services & Configuration
src/mastra/config/AuthenticationService.ts, src/mastra/config/DocumentIndexingService.ts, src/mastra/config/agent-schemas.ts, src/mastra/config/a2a.ts, src/mastra/config/acp.ts
Added AuthenticationService for JWT validation and access policy generation; introduced DocumentIndexingService for document processing orchestration; created comprehensive agent schema definitions (50+ schemas); added A2A and ACP provider configurations.
API Routes
app/api/chat/route.ts, app/api/chat-extra/route.ts, app/api/completion/route.ts
Replaced RuntimeContext with RequestContext in stream configuration; updated context variable names and references.
Utility & Library Updates
lib/client-stream-to-ai-sdk.ts
Changed AI SDK formatter from toAISdkFormat() to toAISdkStream() with explicit { from: "agent" } option.
Configuration & Build
.env.example, next.config.ts, .github/agents/Thinking-Beast-Mode.agent.md, instrumentation.ts
Added ANALYZE environment variable for Next.js Bundle Analyzer; enabled styledJsx compiler; wrapped config with withBundleAnalyzer; expanded agent tools and thinking directives; reorganized OpenTelemetry imports.
Documentation
docs/components/h.md, docs/v1-migration-guide.md, docs/v1.md
Added comprehensive observability/tracing documentation (Custom Metadata, RequestContext extraction, span processors); created detailed v1 migration guide covering tools and tracing API changes; added v1 API documentation index.
Dependencies
package.json
Upgraded Mastra packages from 0.x pre-releases to 1.x beta (\@mastra/ai-sdk, \@mastra/core, \@mastra/deployer, etc.); added \@opentelemetry/exporter-trace-otlp-proto, isolated-vm, pino/pino-pretty; updated various AI provider versions; bumped project version to 1.0.9.
Minor Fixes
app/components/landing-testimonials.tsx, src/mastra/config/ai-gateway.ts, src/mastra/config/tracing.ts, src/mastra/config/upstashMemory.ts, src/mastra/experiments/agent-experiments.ts
Refactored auto-play guard formatting; removed deprecated LangfuseExporter class; deleted complete upstash memory module (upstashMemory, vector APIs); replaced runExperiment with runEvals and removed CLI guard; added newline.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Areas requiring extra attention:

  • RuntimeContext → RequestContext Migration: Verify all agent instruction handlers, model selectors, and context accessors (requestContext.get()) are correctly wired across 25+ agent files and coordinate properly with new context type signatures.
  • Tool Execute Signature Consistency: Ensure all 30+ tools correctly implement the new (inputData, context) signature with proper extraction of writer, requestContext, and tracing span initialization; validate that span lifecycle (creation, attribute updates, end) is consistent across all tools.
  • OpenTelemetry Tracing Refactor: Confirm migration from tracingContext.currentSpan.createChildSpan() to trace.getTracer().startSpan() is complete and consistent; validate span attribute names, error recording with recordException(), and status codes match expected patterns across all files.
  • Scorer ID Addition: Verify all scorers have unique, consistent id fields and that import paths from @mastra/evals/scorers/llm@mastra/evals/scorers/prebuilt are correct; check sampling configurations added to agents (e.g., rate: 0.3–0.5).
  • Storage/Vector ID Assignments: Ensure all storage instances (PostgresStore, UpstashStorage, MongoDBStore, etc.) and vector stores have required id parameters; validate MCP server ID assignment.
  • Package.json Compatibility: Confirm all Mastra 1.x beta package versions are compatible with one another and no transitive dependency conflicts introduced; validate that deprecated packages (0.x versions) are fully removed.
  • Observability Configuration: Review new Observability class instantiation in src/mastra/index.ts (requestContextKeys, spanOutputProcessors, exporters configuration) for correctness and alignment with removed telemetry/DefaultExporter patterns.
  • Breaking API Changes: Validate migration of agent networks (codingTeamNetwork, dataPipelineNetwork, etc.) to new tracing patterns and empty options objects; confirm no internal tracing dependencies remain.
  • Schema & Type Exports: Verify new agent-schemas.ts exports (50+ Zod schemas, agentOutputSchemas mapping) are complete and that all referenced types (ModelMetadata, ModelConfiguration, etc.) are correctly inferred and used.

Possibly related PRs

  • AgentStack#20: Overlapping tool-level refactors including splitting InferUITool imports and switching progress logging from writer.write() to writer.custom('data-tool-progress').
  • AgentStack#10: Modifies the same coordinator files (src/mastra/a2a/codingA2ACoordinator.ts) and updates agent configuration exports and scoring integrations.
  • AgentStack#22: Overlapping modifications to tool IDs, tracing/observability settings, and exports for data-file-manager.ts, document-chunking.tool.ts, pdf-data-conversion.tool.ts, and related tool module indices.

Poem

🐇 Context flows through RequestContext's door,
spans dance with telemetry once more,
tools sing with inputData so bright,
tracing with OpenTelemetry's light—
v1 hops forward, leaving 0.x ashore! 🌿

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a1185e1 and aba3a1e.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (107)
  • .env.example (1 hunks)
  • .github/agents/Thinking-Beast-Mode.agent.md (1 hunks)
  • app/api/chat-extra/route.ts (1 hunks)
  • app/api/chat/route.ts (1 hunks)
  • app/api/completion/route.ts (1 hunks)
  • app/components/landing-testimonials.tsx (1 hunks)
  • docs/components/h.md (1 hunks)
  • docs/v1-migration-guide.md (1 hunks)
  • docs/v1.md (1 hunks)
  • instrumentation.ts (1 hunks)
  • lib/client-stream-to-ai-sdk.ts (2 hunks)
  • next.config.ts (4 hunks)
  • package.json (7 hunks)
  • src/mastra/a2a/a2aCoordinatorAgent.ts (3 hunks)
  • src/mastra/a2a/codingA2ACoordinator.ts (3 hunks)
  • src/mastra/agents/acpAgent.ts (3 hunks)
  • src/mastra/agents/businessLegalAgents.ts (10 hunks)
  • src/mastra/agents/calendarAgent.ts (2 hunks)
  • src/mastra/agents/codingAgents.ts (11 hunks)
  • src/mastra/agents/contentStrategistAgent.ts (2 hunks)
  • src/mastra/agents/copywriterAgent.ts (2 hunks)
  • src/mastra/agents/csv_to_excalidraw.ts (2 hunks)
  • src/mastra/agents/dane.ts (5 hunks)
  • src/mastra/agents/dataExportAgent.ts (2 hunks)
  • src/mastra/agents/dataIngestionAgent.ts (4 hunks)
  • src/mastra/agents/dataTransformationAgent.ts (3 hunks)
  • src/mastra/agents/documentProcessingAgent.ts (3 hunks)
  • src/mastra/agents/editorAgent.ts (5 hunks)
  • src/mastra/agents/evaluationAgent.ts (3 hunks)
  • src/mastra/agents/excalidraw_validator.ts (2 hunks)
  • src/mastra/agents/image.ts (2 hunks)
  • src/mastra/agents/image_to_csv.ts (2 hunks)
  • src/mastra/agents/knowledgeIndexingAgent.ts (3 hunks)
  • src/mastra/agents/learningExtractionAgent.ts (2 hunks)
  • src/mastra/agents/package-publisher.ts (3 hunks)
  • src/mastra/agents/recharts.ts (7 hunks)
  • src/mastra/agents/reportAgent.ts (4 hunks)
  • src/mastra/agents/researchAgent.ts (3 hunks)
  • src/mastra/agents/researchPaperAgent.ts (4 hunks)
  • src/mastra/agents/scriptWriterAgent.ts (4 hunks)
  • src/mastra/agents/sql.ts (4 hunks)
  • src/mastra/agents/stockAnalysisAgent.ts (4 hunks)
  • src/mastra/agents/weather-agent.ts (4 hunks)
  • src/mastra/config/AuthenticationService.ts (1 hunks)
  • src/mastra/config/DocumentIndexingService.ts (1 hunks)
  • src/mastra/config/a2a.ts (1 hunks)
  • src/mastra/config/acp.ts (1 hunks)
  • src/mastra/config/agent-schemas.ts (1 hunks)
  • src/mastra/config/ai-gateway.ts (1 hunks)
  • src/mastra/config/mongodb.ts (3 hunks)
  • src/mastra/config/pg-storage.ts (8 hunks)
  • src/mastra/config/tracing.ts (0 hunks)
  • src/mastra/config/upstash.ts (2 hunks)
  • src/mastra/config/upstashMemory.ts (0 hunks)
  • src/mastra/config/vector/chroma.ts (1 hunks)
  • src/mastra/config/vector/cloudflare.ts (3 hunks)
  • src/mastra/config/vector/pinecone.ts (1 hunks)
  • src/mastra/config/vector/qdrant.ts (1 hunks)
  • src/mastra/experiments/agent-experiments.ts (13 hunks)
  • src/mastra/index.ts (4 hunks)
  • src/mastra/mcp/server.ts (1 hunks)
  • src/mastra/networks/codingTeamNetwork.ts (2 hunks)
  • src/mastra/networks/dataPipelineNetwork.ts (2 hunks)
  • src/mastra/networks/index.ts (2 hunks)
  • src/mastra/networks/reportGenerationNetwork.ts (0 hunks)
  • src/mastra/networks/researchPipelineNetwork.ts (0 hunks)
  • src/mastra/scorers/csv-validity.scorer.ts (2 hunks)
  • src/mastra/scorers/custom-scorers.ts (7 hunks)
  • src/mastra/scorers/factuality.scorer.ts (3 hunks)
  • src/mastra/scorers/financial-scorers.ts (5 hunks)
  • src/mastra/scorers/script-scorers.ts (4 hunks)
  • src/mastra/scorers/sql-validity.scorer.ts (2 hunks)
  • src/mastra/scorers/structure.scorer.ts (5 hunks)
  • src/mastra/scorers/tone-consistency.scorer.ts (3 hunks)
  • src/mastra/scorers/weather-scorer.ts (4 hunks)
  • src/mastra/tools/alpha-vantage.tool.ts (10 hunks)
  • src/mastra/tools/arxiv.tool.ts (12 hunks)
  • src/mastra/tools/browser-tool.ts (12 hunks)
  • src/mastra/tools/calendar-tool.ts (13 hunks)
  • src/mastra/tools/code-analysis.tool.ts (3 hunks)
  • src/mastra/tools/code-chunking.ts (1 hunks)
  • src/mastra/tools/code-search.tool.ts (4 hunks)
  • src/mastra/tools/copywriter-agent-tool.ts (5 hunks)
  • src/mastra/tools/csv-to-json.tool.ts (3 hunks)
  • src/mastra/tools/data-file-manager.ts (26 hunks)
  • src/mastra/tools/data-processing-tools.ts (24 hunks)
  • src/mastra/tools/data-validator.tool.ts (3 hunks)
  • src/mastra/tools/diff-review.tool.ts (2 hunks)
  • src/mastra/tools/document-chunking.tool.ts (20 hunks)
  • src/mastra/tools/editor-agent-tool.ts (5 hunks)
  • src/mastra/tools/evaluateResultTool.ts (4 hunks)
  • src/mastra/tools/execa-tool.ts (3 hunks)
  • src/mastra/tools/extractLearningsTool.ts (4 hunks)
  • src/mastra/tools/financial-chart-tools.ts (18 hunks)
  • src/mastra/tools/find-references.tool.ts (5 hunks)
  • src/mastra/tools/find-symbol.tool.ts (6 hunks)
  • src/mastra/tools/finnhub-tools.ts (39 hunks)
  • src/mastra/tools/fs.ts (3 hunks)
  • src/mastra/tools/github.ts (18 hunks)
  • src/mastra/tools/json-to-csv.tool.ts (3 hunks)
  • src/mastra/tools/jwt-auth.tool.ts (2 hunks)
  • src/mastra/tools/multi-string-edit.tool.ts (5 hunks)
  • src/mastra/tools/pdf-data-conversion.tool.ts (8 hunks)
  • src/mastra/tools/pdf.ts (2 hunks)
  • src/mastra/tools/pg-sql-tool.ts (3 hunks)
  • src/mastra/tools/pnpm-tool.ts (12 hunks)
  • src/mastra/tools/polygon-tools.ts (48 hunks)
⛔ Files not processed due to max files limit (19)
  • src/mastra/tools/serpapi-academic-local.tool.ts
  • src/mastra/tools/serpapi-news-trends.tool.ts
  • src/mastra/tools/serpapi-search.tool.ts
  • src/mastra/tools/serpapi-shopping.tool.ts
  • src/mastra/tools/test-generator.tool.ts
  • src/mastra/tools/tests/csv-to-json.tool.test.ts
  • src/mastra/tools/tests/data-validator.tool.test.ts
  • src/mastra/tools/tests/json-to-csv.tool.test.ts
  • src/mastra/tools/tests/serpapi-news-trends.tool.test.ts
  • src/mastra/tools/tests/serpapi-search.tool.test.ts
  • src/mastra/tools/tests/web-scraper-tool.test.ts
  • src/mastra/tools/weather-tool.ts
  • src/mastra/tools/web-scraper-tool.ts
  • src/mastra/tools/write-note.ts
  • src/mastra/types/excalidraw-to-svg.d.ts
  • src/mastra/types/svgjson.d.ts
  • src/mastra/workflows/content-review-workflow.ts
  • src/mastra/workflows/content-studio-workflow.ts
  • src/mastra/workflows/document-processing-workflow.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR migrates the codebase to Mastra v1 by replacing the deprecated tracing API with OpenTelemetry's standard API and updating tool execution patterns to align with the new framework architecture.

Key changes:

  • Replaced Mastra-specific tracing (AISpanType, InternalSpans, TracingContext) with OpenTelemetry API (trace, SpanStatusCode)
  • Updated tool execution signatures from { context, tracingContext, runtimeContext, writer } to (inputData, context) pattern
  • Migrated from generate() to stream() for agent responses with inline JSON parsing
  • Renamed RuntimeContext to RequestContext throughout the codebase

Reviewed changes

Copilot reviewed 127 out of 136 changed files in this pull request and generated 3 comments.

File Description
workflows/*.ts Updated tracing to use OpenTelemetry API; migrated agent calls to streaming pattern with fallback parsing
tools/*.ts Converted tool execution signatures; replaced Mastra tracing with OpenTelemetry spans
tools/tests/*.ts Updated test imports for new observability package path
networks/reportGenerationNetwork.ts Removed unused InternalSpans import

});

const {value} = context
// const {value} = input // unused
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the commented-out unused variable declaration on line 147. Dead code should be removed rather than commented out.

Suggested change
// const {value} = input // unused

Copilot uses AI. Check for mistakes.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
import { log } from '../config/logger'
import type { RequestContext } from '@mastra/core/request-context';
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate import of RequestContext from '@mastra/core/request-context' on lines 2 and 6. Remove the duplicate import on line 6.

Suggested change
import type { RequestContext } from '@mastra/core/request-context';

Copilot uses AI. Check for mistakes.
Comment on lines +36 to +43
execute: async (inputData, context) => {
const writer = context?.writer;
const tracingContext = context?.tracingContext;

const span = tracingContext?.currentSpan?.createChildSpan({
type: AISpanType.TOOL_CALL,
name: 'read-pdf',
input: { pdfPath: context.pdfPath },
tracingPolicy: { internal: InternalSpans.TOOL }
input: { pdfPath: inputData.pdfPath },
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tracing code on lines 40-44 still uses the deprecated Mastra-specific API (tracingContext?.currentSpan?.createChildSpan, AISpanType.TOOL_CALL) instead of the OpenTelemetry API. This is inconsistent with the migration goal. Replace with trace.getTracer() and tracer.startSpan() pattern as used in other files.

Copilot uses AI. Check for mistakes.
@github-actions
Copy link

🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details.

Copy link

Copilot AI commented Dec 10, 2025

@ssdeanx I've opened a new pull request, #30, to work on those changes. Once the pull request is ready, I'll request review from you.

Copy link
Contributor

@github-advanced-security github-advanced-security bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remark-lint (reported by Codacy) found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

@ssdeanx ssdeanx merged commit 46f043a into main Dec 10, 2025
45 of 47 checks passed
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ssdeanx, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request represents a major upgrade to Mastra v1, focusing on modernizing the core architecture and enhancing key functionalities. It introduces new services for authentication and document indexing, integrates advanced AI providers, and standardizes data structures through Zod schemas. A significant portion of the changes involves a complete overhaul of the observability and tracing system to align with OpenTelemetry, ensuring better monitoring and debugging capabilities. These updates aim to provide a more robust, scalable, and developer-friendly platform for building AI applications.

Highlights

  • Mastra v1 Migration: The project has been migrated to Mastra v1, incorporating significant updates to core services, AI provider integrations, and observability. This includes updating agent and tool configurations to align with the new API surface.
  • New Core Services: Introduced AuthenticationService for robust JWT verification and dynamic access policy generation, and DocumentIndexingService for advanced document processing, chunking, and embedding capabilities with security tag extraction.
  • Enhanced AI Provider Integrations: Added support for A2A (Agent-to-Agent) and ACP (Agent Communication Protocol) AI providers, enabling streaming text responses and advanced agent orchestration, particularly with Gemini ACP.
  • Standardized Agent Schemas: Comprehensive Zod schemas have been defined for various agent components, including JWT claims, access filters, document contexts, and output formats, ensuring consistent data structures and validation across the system.
  • Observability and Tracing Overhaul: The entire observability and tracing system has been refactored to use the new @mastra/observability package, replacing the old telemetry configuration and ai-tracing modules. This includes updating span creation, error handling, and context propagation to align with OpenTelemetry standards.
  • Tooling and Agent Updates: Numerous agents and tools have been updated to reflect the new RequestContext paradigm (replacing RuntimeContext), adopt the (inputData, context) signature for execute functions, and integrate with the new OpenTelemetry-based tracing mechanisms.
  • Documentation for v1 Migration: Initial API documentation and a detailed migration guide for Mastra v1 have been added, covering changes to Tools and Tracing to assist developers in upgrading their projects.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request primarily focuses on a major version upgrade of the Mastra framework to v1, entailing significant changes to observability, tracing, and context handling. Key updates include renaming RuntimeContext to RequestContext across numerous agent and API files, and a complete overhaul of the tracing system to align with OpenTelemetry standards, removing the old InternalSpans and tracingPolicy options from agents and tools. Many tools now explicitly use trace.getTracer().startSpan() and span.setAttributes() for detailed tracing, addressing a review comment about incomplete tracing migration. The package.json reflects these changes with numerous @mastra/* dependencies updated to 1.0.0-beta versions, and new packages like @mastra/observability and a2a-ai-provider introduced. Documentation files (h.md, v1-migration-guide.md, v1.md) have been added or updated to reflect these architectural shifts, including a comprehensive migration guide for tools and tracing. Minor changes include adding ANALYZE='false' to .env.example, simplifying styledJsx config, and integrating @next/bundle-analyzer in next.config.ts. Several review comments highlight the incomplete migration of tracing in tools, leading to runtime errors, and the need to use span.setAttributes() for capturing output data before span.end(). Other comments point out unused parameters and suggest more descriptive filenames for new documentation.

Comment on lines 23 to 27
const span = tracingContext?.currentSpan?.createChildSpan({
type: AISpanType.TOOL_CALL,
name: 'fs-tool',
input: { action: context.action, file: context.file },
tracingPolicy: { internal: InternalSpans.ALL }
input: { action: inputData.action, file: inputData.file },
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The tracing implementation in this tool is incomplete and will cause a runtime error. tracingContext is from the old system and is no longer available on the context object. Additionally, AISpanType is no longer imported. This tool needs to be fully migrated to the new OpenTelemetry-based tracing, similar to other tools in this PR.

Suggested change
const span = tracingContext?.currentSpan?.createChildSpan({
type: AISpanType.TOOL_CALL,
name: 'fs-tool',
input: { action: context.action, file: context.file },
tracingPolicy: { internal: InternalSpans.ALL }
input: { action: inputData.action, file: inputData.file },
});
const tracer = trace.getTracer('fs-tool', '1.0.0');
const span = tracer.startSpan('fs-tool', {
attributes: {
'tool.id': 'fsTool',
'tool.input.action': inputData.action,
'tool.input.file': inputData.file,
}
});

format: "aisdk",
});
const runtimeContext = new RuntimeContext();
const requestContext = new RequestContext();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The requestContext variable is initialized but never used. This appears to be dead code and should be removed for clarity. If it was intended to be used, it should be passed to the myAgent.stream call.

@@ -0,0 +1,420 @@
Adding Custom Metadata
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The filename h.md is not descriptive. Based on the content, which appears to be about observability and tracing, a more informative name like observability-tracing-guide.md or custom-metadata-and-tracing.md would make it easier for developers to find and understand its purpose.

}

export async function runAllExperiments() {
export async function runAllExperiments(p0: unknown) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The function runAllExperiments has an unused parameter p0. This should be removed to improve code clarity and avoid confusion.

Suggested change
export async function runAllExperiments(p0: unknown) {
export async function runAllExperiments() {

},
},
processors: [new TokenLimiter(1048576)],
processors: [],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

I noticed the TokenLimiter processor has been removed from the pgMemory configuration. Was this intentional? If so, is token limiting now handled elsewhere, or is it no longer required for this memory setup? Understanding the reasoning will help ensure a safeguard hasn't been unintentionally removed.

// But I can't replicate `end({output})` directly.
// I will set attributes and then end.

apiSpan?.end();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The migration to the new OpenTelemetry API seems to have resulted in a loss of tracing information. The previous implementation recorded output details like status and data size in the span. The new OpenTelemetry span.end() method doesn't accept arguments. To preserve this valuable information, you should use span.setAttributes() before calling span.end(). This pattern appears in multiple places in this file and other tool files (polygon-tools.ts, serpapi-*.ts, etc.) and should be applied consistently.

      apiSpan.setAttributes({
        'http.status_code': response.status,
        'http.status_text': response.statusText,
        'response.data.size': JSON.stringify(data).length,
        'duration_ms': apiDuration
      });
      apiSpan.end();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants