Building MCP Integration in Astreus

Connect agents to external tools via Model Context Protocol. File systems, databases, APIs - through a standardized interface.

The Model Context Protocol (MCP) provides a standardized way for AI agents to interact with external systems. Instead of building custom integrations for every tool, database, or API, you use a universal protocol that works across all resources. ## Why MCP Matters AI agents need access to real-world data and systems to be useful. Without file access, database connections, or API capabilities, they're limited to pure reasoning. MCP solves this by creating a standard interface between agents and external resources, similar to how HTTP standardized web communication. ## Setting Up Your Environment Start by installing Astreus and configuring your environment variables. You'll need API keys for the AI provider and database connection strings. ```bash npm install @astreus-ai/astreus ``` Then configure your environment: ```env OPENAI_API_KEY=your_api_key_here DB_URL=sqlite://./astreus.db ``` These credentials allow your agent to authenticate with AI providers and access the database for state management. ## The Core API Method Astreus provides the `addMCPServers()` method to connect agents with MCP servers. This is the primary way to enable external tool access. ```typescript await mainAgent.addMCPServers([mcpConfig]); ``` The method accepts an array of server configurations, allowing you to add multiple capabilities to your agent simultaneously. ## Configuring an MCP Server Each MCP server configuration requires three key properties: a name identifier, the command to execute, and arguments including the server package and working directory. ```typescript const mcpConfig = { name: 'filesystem', command: 'npx', args: [ '@modelcontextprotocol/server-filesystem', '/path/to/working/directory' ] }; await mainAgent.addMCPServers([mcpConfig]); ``` This configuration gives your agent filesystem access through the official MCP filesystem server package. The agent can now read and write files within the specified directory. ## Multiple Server Integration Agents often need multiple capabilities. You can add different MCP servers to compose functionality. ```typescript await mainAgent.addMCPServers([ { name: 'filesystem', command: 'npx', args: ['@modelcontextprotocol/server-filesystem', process.cwd()] }, { name: 'database', command: 'npx', args: ['@modelcontextprotocol/server-sqlite', './data.db'] } ]); ``` This setup provides both filesystem and database access. The agent automatically decides which tool to use based on the task requirements. ## Building a File Analysis Workflow The documentation demonstrates a practical file analysis workflow that leverages the filesystem MCP server. This pattern shows how to enable agents to read and write files while managing tasks through graph-based execution. The workflow approach uses dependencies and priorities to coordinate tasks. Each node in the graph represents a specific operation, and edges define execution order. ```typescript import { Agent } from '@astreus-ai/astreus'; const analyzer = await Agent.create({ name: 'File Analyzer', model: 'gpt-4o', systemPrompt: 'You analyze files and provide insights about their structure and content.' }); // Add filesystem access await analyzer.addMCPServers([{ name: 'filesystem', command: 'npx', args: [ '@modelcontextprotocol/server-filesystem', '/project/directory' ] }]); // Agent can now read and analyze files const result = await analyzer.ask( 'Analyze all TypeScript files and summarize the architecture' ); ``` The agent uses the MCP filesystem server to access files, reads their contents, and generates analysis based on what it finds. ## Graph-Based Task Execution Astreus supports graph-based workflows where tasks have dependencies and priorities. This enables complex multi-step operations that coordinate between different MCP tools. You define nodes representing individual tasks and edges showing dependencies. The system ensures tasks execute in the correct order, with each step building on previous results. ```typescript const workflow = { nodes: [ { id: 'read-config', task: 'Read the configuration file', priority: 1 }, { id: 'analyze', task: 'Analyze the configuration for issues', dependsOn: ['read-config'], priority: 2 }, { id: 'generate-report', task: 'Generate a summary report', dependsOn: ['analyze'], priority: 3 } ] }; ``` This structure ensures the agent reads the configuration before analyzing it, and completes analysis before generating the report. Dependencies prevent execution order issues. ## Working with the Filesystem Server The filesystem MCP server is one of the most commonly used tools. It provides file read, write, and directory listing capabilities within the specified working directory. ```typescript await agent.addMCPServers([{ name: 'project-files', command: 'npx', args: [ '@modelcontextprotocol/server-filesystem', '/Users/username/projects/myapp' ] }]); const response = await agent.ask( 'List all package.json files and extract their dependencies' ); ``` The agent can traverse directories, read package.json files, and extract information. The filesystem server enforces boundaries, preventing access outside the working directory. ## Security Considerations Always follow the principle of least privilege. Only grant agents access to directories and resources they absolutely need. The working directory parameter in MCP server configuration creates a security boundary. ```typescript // Good: Restricted to specific project directory await agent.addMCPServers([{ name: 'filesystem', command: 'npx', args: ['@modelcontextprotocol/server-filesystem', '/app/data'] }]); // Risky: Full filesystem access await agent.addMCPServers([{ name: 'filesystem', command: 'npx', args: ['@modelcontextprotocol/server-filesystem', '/'] }]); ``` The first configuration limits the agent to the `/app/data` directory. The second grants access to the entire filesystem, which could be dangerous if the agent behaves unexpectedly. ## Complete Example Setup Here's how to clone and set up the official MCP integration example from Astreus. ```bash # Clone the example repository git clone https://github.com/astreus-ai/examples cd examples/mcp-integration # Install dependencies npm install # Configure environment cp .env.example .env # Edit .env with your API keys # Run the example npm start ``` The example demonstrates file analysis with the filesystem MCP server. It shows best practices for configuration, error handling, and workflow structure. ## Package-Only Installation If you prefer building from scratch rather than using the example, install just the Astreus package and configure it yourself. ```bash npm install @astreus-ai/astreus ``` Then create your agent and add MCP servers as needed. This approach gives you full control over the architecture and configuration. ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'Custom Agent', model: 'gpt-4o', systemPrompt: 'Your custom instructions here' }); await agent.addMCPServers([{ name: 'filesystem', command: 'npx', args: ['@modelcontextprotocol/server-filesystem', process.cwd()] }]); ``` ## Available MCP Servers The Model Context Protocol ecosystem includes servers for many common tools. The official packages provide filesystem, SQLite, PostgreSQL, and other capabilities. - `@modelcontextprotocol/server-filesystem` - File and directory access - `@modelcontextprotocol/server-sqlite` - SQLite database queries - `@modelcontextprotocol/server-postgres` - PostgreSQL integration - `@modelcontextprotocol/server-github` - GitHub API access Each server follows the same configuration pattern with name, command, and args properties. You can mix different servers to compose the exact capabilities your agent needs. ## Error Handling MCP operations can fail due to permissions, missing files, or server issues. Handle errors gracefully to build robust agents. ```typescript try { const result = await agent.ask( 'Read the configuration file' ); console.log(result); } catch (error) { console.error('Task failed:', error.message); // Handle error appropriately } ``` Proper error handling ensures your agent fails gracefully when operations don't succeed. ## Next Steps The `addMCPServers()` method is the foundation for giving agents real-world capabilities. Start with the filesystem server to enable file access, then add additional servers as your needs grow. For complete implementation details and additional configuration options, consult the full Astreus documentation. The framework continues to evolve with new MCP server support and enhanced integration capabilities. Explore the official examples repository at github.com/astreus-ai/examples to see these patterns in action and learn advanced techniques for building MCP-integrated agents. This experiment is written for Astreus v0.5.37. Please ensure you are using a compatible version.