npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@t3ta/claude-code-mastra

v0.0.1

Published

Claude Code SDK integration for Mastra framework

Readme

Claude Code × Mastra Agent Integration

This library integrates the Claude Code TypeScript SDK as an Agent within the Mastra framework.

Overview

This library adapts the Claude Code SDK to the Mastra Agent interface, enabling powerful coding assistance features of Claude Code within the Mastra framework.

Features

  • Mastra Agent Compatible: Fully implements the Mastra Framework Agent interface
  • Custom Tools: Supports Mastra Agent's tools feature
  • MCP External Tools: Integrates external tools via Model Context Protocol
  • Streaming Support: Real-time response processing
  • Session Management: Tracks session state and manages resources
  • Error Handling: Robust error handling mechanisms
  • Configurable: Supports Claude Code-specific options
  • Type Safe: Complete TypeScript type definitions

Installation

npm install @anthropic-ai/claude-code @mastra/core

Basic Usage

Simple Generation

import { ClaudeCodeAgent } from './claude-code-agent.js';

const agent = new ClaudeCodeAgent({
  maxTurns: 3,
  permissionMode: 'default'
});

const response = await agent.generate(
  'Write a TypeScript function to calculate fibonacci numbers'
);

console.log(response.content);
console.log(response.metadata); // Session info, cost, etc.

Streaming

for await (const chunk of agent.stream('Create a REST API with Express.js')) {
  if (chunk.type === 'content') {
    console.log('Content:', chunk.data.content);
  } else if (chunk.type === 'complete') {
    console.log('Total cost:', chunk.data.totalCost);
  }
}

Configuration Options

interface ClaudeCodeAgentOptions {
  maxTurns?: number;                    // Max turns (default: 10)
  allowedTools?: string[];              // Allowed tools
  permissionMode?: 'default' | 'acceptEdits' | 'bypassPermissions';
  workingDirectory?: string;            // Working directory
  timeout?: number;                     // Timeout (ms, default: 300000)
}

API

ClaudeCodeAgent

constructor(options?: ClaudeCodeAgentOptions)

Creates a new agent instance.

generate(prompt: string, options?: Partial): Promise

Generates a single response.

stream(prompt: string, options?: Partial): AsyncIterable

Generates streaming responses.

getSessionInfo(sessionId: string): SessionInfo | undefined

Retrieves session information.

getAllActiveSessions(): SessionInfo[]

Retrieves all active sessions.

updateClaudeCodeOptions(options: Partial): void

Updates default options.

Response Format

MastraResponse

interface MastraResponse {
  content: string;
  metadata?: {
    sessionId?: string;
    cost?: number;
    duration?: number;
    totalTurns?: number;
  };
}

MastraStreamChunk

interface MastraStreamChunk {
  type: 'content' | 'metadata' | 'error' | 'complete';
  data: any;
}

Session Management

The agent automatically manages sessions and provides:

  • Automatic Session Creation: Creates a new session for each query
  • Cost Tracking: Tracks execution cost
  • Resource Management: Automatic cleanup after 30 seconds
  • Session Info: Monitors active sessions

Error Handling

try {
  const response = await agent.generate('invalid request');
} catch (error) {
  console.error('Generation failed:', error.message);
}

// Error handling in streaming
for await (const chunk of agent.stream('prompt')) {
  if (chunk.type === 'error') {
    console.error('Stream error:', chunk.data.error);
    break;
  }
}

Using Custom Tools

Tool Definition and Execution

import { ClaudeCodeAgent } from './claude-code-agent.js';
import { z } from 'zod';
import type { ToolAction } from '@mastra/core';

// Define a custom tool
const weatherTool: ToolAction = {
  description: 'Get weather information for a city',
  inputSchema: z.object({
    city: z.string(),
    unit: z.enum(['celsius', 'fahrenheit']).optional()
  }),
  execute: async ({ context }) => {
    // Actual API call, etc.
    return {
      city: context.city,
      temperature: 22,
      unit: context.unit || 'celsius',
      conditions: 'Sunny'
    };
  }
};

// Create an agent with tools
const agent = new ClaudeCodeAgent({
  name: 'weather-agent',
  instructions: 'You are a weather assistant with access to weather data.',
  model: 'claude-3-5-sonnet-20241022',
  tools: {
    getWeather: weatherTool
  }
});

// Direct tool execution
const weatherData = await agent.executeTool('getWeather', {
  city: 'Tokyo',
  unit: 'celsius'
});

// Using the agent
const response = await agent.generate(
  'What is the weather like in Tokyo?'
);

Dynamic Tool Management

// Add a tool
agent.addTool('calculator', {
  description: 'Perform calculations',
  inputSchema: z.object({
    expression: z.string()
  }),
  execute: async ({ context }) => {
    // Calculation logic
    return { result: eval(context.expression) };
  }
});

// Check available tools
console.log(agent.getToolNames()); // ['getWeather', 'calculator']
console.log(agent.getToolDescriptions());

// Remove a tool
agent.removeTool('calculator');

Advanced Usage

Dynamic Option Updates

const agent = new ClaudeCodeAgent();

// Update default options
agent.updateClaudeCodeOptions({
  maxTurns: 5,
  allowedTools: ['Edit', 'Read', 'Write'],
  permissionMode: 'bypassPermissions'
});

// Override options for a specific query
const response = await agent.generate('prompt', {
  maxTurns: 1,
  timeout: 30000
});

Session Monitoring

// Monitor active sessions
console.log('Active sessions:', agent.getAllActiveSessions().length);

// Get info for a specific session
const sessionInfo = agent.getSessionInfo(sessionId);
if (sessionInfo) {
  console.log('Session cost:', sessionInfo.totalCost);
  console.log('Session duration:', Date.now() - sessionInfo.startTime);
}

File Structure

  • claude-code-agent.ts - Main ClaudeCodeAgent class
  • message-converter.ts - Message conversion utilities
  • types.ts - TypeScript type definitions
  • utils.ts - Helper functions and session management
  • example.ts - Usage examples and demo code

Requirements

  • Node.js 18+
  • TypeScript 4.9+
  • @anthropic-ai/claude-code ^1.0.35
  • @mastra/core ^0.10.8

Authentication

Claude Code authentication is required:

# Login to Claude Code
claude login

# Or set via environment variable
export ANTHROPIC_API_KEY=your_api_key

Testing

This project includes a comprehensive test suite:

Test Types

Unit Tests

npm run test:unit

Tests individual components and methods (with mocks).

Component Integration Tests

npm run test:integration

Tests integration between components (with mocks).

E2E Tests

npm run test:e2e

Tests integration with the actual Claude Code SDK (real API calls).

⚠️ Note: E2E tests require:

  • Claude Code CLI setup: claude login
  • Valid Anthropic API key
  • Internet connection
  • Possible API credit consumption

All Tests

npm run test        # All tests except E2E
npm run test:all    # Run all tests
npm run test:watch  # Watch mode
npm run test:ui     # UI test runner
npm run test:coverage # With coverage

Test Results

  • 73 unit/integration tests
  • 9 E2E tests
  • Full coverage: All major features covered
  • Performance tests: Response time and concurrency
  • Error handling tests: Abnormal case verification

Development

# Type checking during development
npm run typecheck

# Build
npm run build

# Test in watch mode
npm run test:watch

Security and Limitations

Current Limitations

Currently, the built-in tool restriction features (allowedTools/disallowedTools) of the Claude Code SDK may not work as expected. Please note the following security risks:

High Risk

  1. Unintended File Operations

    // If Write, Edit, Bash tools are not restricted
    agent.generate("Delete important files");
    // → May actually perform file operations
  2. Arbitrary Command Execution

    // Arbitrary system command execution via Bash tool
    agent.generate("npm install malicious-package");
    // → May change the system
  3. System Resource Abuse

    // Unlimited file reading
    agent.generate("Read all files");
    // → Heavy I/O load

Recommended Countermeasures

  1. Careful control in production

    • Only process trusted input
    • Run in a sandbox environment without important files
    • Set appropriate permissions
  2. Prefer Mastra tools

    // Define and use safe custom tools
    const agent = new ClaudeCodeAgent({
      tools: {
        safeTool: {
          description: 'Performs only safe operations',
          // Controlled implementation
        }
      }
    });
  3. Session Monitoring

    // Monitor session info and control cost
    const sessions = agent.getAllActiveSessions();
    sessions.forEach(session => {
      if (session.totalCost > threshold) {
        agent.stopSession(session.sessionId);
      }
    });

Planned Fixes

Tool restriction features will be fixed in future updates. Currently, the core features (tool execution, result return, session management) work as intended.

License

MIT

Author

Takahito Mita