Smart MCP Agent Template
A Mastra template for creating intelligent AI agents that can dynamically discover, install, and use MCP (Model Context Protocol) servers in run time. This template provides a foundation for building agents that can automatically find and integrate external services through the MCP ecosystem.
š Features
- Dynamic MCP Server Discovery: Search the Smithery registry for available MCP servers
- Automatic Server Installation: Add servers to your agent's configuration dynamically
- Persistent Configuration: Servers are permanently added to the codebase
- File System Access: Built-in filesystem MCP server for project file operations
- Memory Management: LibSQL-based memory storage for agent state
- Type Safety: Full TypeScript support with Zod schema validation
šļø Project Structure
1src/
2āāā mastra/
3ā āāā agents/
4ā ā āāā smart-mcp-agent.ts # Main AI agent with MCP capabilities
5ā āāā tools/
6ā ā āāā add-mcp-server.ts # Dynamically add MCP servers to config
7ā ā āāā discover-servers.ts # Search Smithery registry for servers
8ā ā āāā list-servers.ts # List currently configured servers
9ā āāā index.ts # Mastra configuration
10ā āāā mcp.ts # MCP client configuration
11ā āāā types.ts # TypeScript type definitions
š ļø Installation
-
Clone the template:
1npx create-mastra@latest template-smart-mcp-agent 2cd template-smart-mcp-agent
-
Install dependencies:
npm install
-
Set up environment variables:
1cp .env.example .env 2# Edit .env with your API keys
-
Start development server:
npm run dev
š§ Configuration
Environment Variables
Variable | Description | Required |
---|---|---|
OPENAI_API_KEY | OpenAI API key for agent model | Yes |
SMITHERY_API_KEY | Smithery registry API key | Yes |
Agent Configuration
1import { smartMcpAgent } from './src/mastra/agents/smart-mcp-agent';
2
3// Agent is configured with:
4// - OpenAI GPT-4o-mini model
5// - LibSQL memory storage
6// - Dynamic MCP server management
š Workflow
The Smart MCP Agent follows this workflow:
- Discovery: Use
discover-servers
to search for MCP servers on Smithery - Installation: Use
add-mcp-server
to dynamically add servers to the configuration - Verification: Use
list-servers
to confirm installation - Usage: Access server tools through the agent
Example Usage
1// Search for web search servers
2await discoverServersTool.execute({
3 context: { query: "web search", limit: 5 }
4});
5
6// Add a web search server
7await addMcpServerTool.execute({
8 context: {
9 name: "websearch",
10 serverId: "@Aas-ee/open-websearch",
11 description: "Web search capabilities"
12 }
13});
14
15// List configured servers
16await listServersTool.execute({ context: {} });
š ļø Tools
Add MCP Server Tool
Dynamically adds MCP servers to the mcp.ts
configuration file.
Input Schema:
1{
2 name: z.string().min(1), // Server name (e.g., "websearch")
3 serverId: z.string().min(1), // Full server ID (e.g., "@Aas-ee/open-websearch")
4 description: z.string().optional() // Optional description
5}
Features:
- Automatically converts server names to valid JavaScript identifiers
- Updates the
mcp.ts
file with proper configuration - Triggers automatic server restart to load new servers
- Provides clear feedback and next steps
Discover Servers Tool
Searches the Smithery registry for available MCP servers.
Input Schema:
1{
2 query: z.string(), // Search query
3 limit: z.number().int().min(1).max(20).optional() // Result limit
4}
Features:
- Searches Smithery registry with optional API key
- Returns server details including name, description, and usage stats
- Graceful fallback if API is unavailable
List Servers Tool
Lists all currently configured MCP servers.
Features:
- Reads the current
mcp.ts
configuration - Identifies server types (Smithery, filesystem, etc.)
- Shows server IDs and configuration details
- Provides clear status information
š Server Management
Adding Servers
When you add a server using add-mcp-server
:
- Configuration Update: The server is added to
src/mastra/mcp.ts
- Automatic Restart: Mastra server restarts to load the new server
- Persistence: Server configuration persists across restarts
- Verification: Use
list-servers
to confirm successful addition
Server Types
- Smithery Servers: Remote MCP servers hosted on Smithery
- Filesystem Server: Local filesystem access for project files
- Custom Servers: Any MCP-compatible server
Current Configuration
The template comes with these pre-configured servers:
- textEditor: Filesystem access for project files
- geeknews: Tech news and updates
- aidaily: AI daily news and insights
š”ļø Error Handling
The template includes comprehensive error handling:
- MCP Connection Failures: Graceful handling of server connection issues
- File System Errors: Safe file operations with proper error messages
- API Rate Limiting: Built-in retry logic for external API calls
- Validation Errors: Zod schema validation with clear error messages
š Development
Available Scripts
npm run dev
- Start development server with hot reloadnpm run build
- Build for productionnpm run start
- Start production server
Development Workflow
- Start the dev server:
npm run dev
- Access the playground: http://localhost:4111
- Test agent interactions: Use the playground to interact with the agent
- Add new servers: Use the agent to discover and add MCP servers
- Monitor logs: Check terminal output for server status and errors
š API Reference
Agent
The smartMcpAgent
provides:
- Model: OpenAI GPT-4o-mini
- Memory: LibSQL-based persistent storage
- Tools: Dynamic MCP server management tools
- Instructions: Comprehensive workflow guidance
MCP Client
The MCP client (buildMcp
) manages:
- Server Connections: Automatic connection to configured servers
- Tool Discovery: Dynamic tool loading from MCP servers
- Error Recovery: Graceful handling of connection issues
- Heartbeat Management: Automatic connection maintenance
š¤ Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
š License
ISC License - see LICENSE file for details.