Back to Articles

Agenspy: Bringing Protocol-First Architecture to DSPy's Agent Ecosystem

[ View on GitHub ]

Agenspy: Bringing Protocol-First Architecture to DSPy’s Agent Ecosystem

Hook

DSPy agents weren’t listed in Google’s A2A Agent Directory. One framework decided to fix that by rethinking how agents communicate—not through individual tools, but through standardized protocols.

Context

DSPy has carved out a unique niche in the AI agent landscape with its optimization-focused approach to prompt engineering and module composition. But it had a blind spot: while frameworks like LangChain and LlamaIndex were adopting protocol-first architectures—embracing standards like the Model Context Protocol (MCP) and Google’s Agent2Agent (A2A)—DSPy remained firmly tool-first. Every MCP tool had to be manually converted into a DSPy.Tool, creating friction and keeping DSPy agents out of emerging protocol directories.

Agenspy emerged from an enhancement proposal filed on the DSPy GitHub repository to demonstrate how DSPy could evolve beyond tool-first thinking. Rather than integrating protocols as afterthoughts, Agenspy rebuilds the foundation: agents communicate through protocol layers that abstract away individual tool implementations. This architectural shift positions DSPy agents to participate in the next generation of multi-agent systems, where standardized communication protocols—not proprietary tool APIs—define how agents discover capabilities, negotiate interactions, and collaborate across organizational boundaries.

Technical Insight

DSPy Core

Agenspy Framework

Protocol Implementations

Agent Request

Protocol Commands

Route

Route

Inherit Patterns

Inference

Response

Prediction

Result

Client Application

BaseAgent

DSPy Module Extension

Protocol Layer

Connection & Session Mgmt

MCP Protocol

Python/Node.js

Agent2Agent Protocol

DSPy Modules

ChainOfThought/ReAct

Language Model

GPT-4/etc

System architecture — auto-generated

Agenspy introduces a three-tier architecture that sits atop DSPy’s module system. At the base is the DSPy Agent Layer, leveraging core patterns like ChainOfThought and ReAct. Above that, a Protocol Layer manages connections, capabilities, and session state across multiple protocol implementations. At the top, Protocol Implementations provide concrete adapters for MCP, Agent2Agent, and future standards.

The fundamental building block is the BaseAgent class, which extends DSPy’s module system while adding protocol awareness. Here’s how you create a custom agent that inherits both DSPy’s optimization capabilities and protocol communication:

import asyncio
import dspy
from agenspy import BaseAgent
from typing import Dict, Any

class CodeReviewAgent(BaseAgent):
    def __init__(self, name: str):
        super().__init__(name)
        
    async def review_code(self, code: str, language: str) -> Dict[str, Any]:
        return {
            "score": 0.85,
            "issues": ["Consider adding error handling", "Document this function"],
            "suggestions": ["Use list comprehension for better performance"]
        }
    
    async def forward(self, **kwargs) -> dspy.Prediction:
        code = kwargs.get("code", "")
        language = kwargs.get("language", "python")
        result = await self.review_code(code, language)
        return dspy.Prediction(**result)

async def main():
    lm = dspy.LM('openai/gpt-4o-mini')
    dspy.configure(lm=lm)
    
    agent = CodeReviewAgent("code-reviewer")
    result = await agent(code="def add(a, b): return a + b", language="python")
    print("Review Results:", result)

if __name__ == "__main__":
    asyncio.run(main())

Notice the async-first design—every agent method returns coroutines, making Agenspy suitable for production deployments where blocking I/O would kill throughput.

For MCP integration, Agenspy appears to provide mechanisms for connecting to MCP servers, though the specific API for connection establishment and capability discovery is not fully documented in the README. The protocol layer handles capability exchange and wraps discovered tools as DSPy-compatible operations.

The experimental MultiProtocolAgent takes this further by enabling simultaneous connections to multiple protocol implementations. An agent can potentially query both an MCP server for GitHub operations and an Agent2Agent directory for specialized analysis services, though the exact routing mechanism is not detailed in available documentation. This creates a potentially interoperable agent that transcends single-protocol limitations.

Agenspy also provides server implementations, not just clients. The PythonMCPServer class lets you expose custom tools as MCP endpoints:

from agenspy.servers.mcp_python_server import PythonMCPServer
import asyncio

class CustomMCPServer(PythonMCPServer):
    def __init__(self, port: int = 8080):
        super().__init__(name="custom-mcp-server", port=port)
        self.register_tool(
            name="custom_operation",
            description="A custom operation that processes parameters",
            parameters={
                "type": "object",
                "properties": {
                    "param1": {"type": "string", "description": "First parameter"},
                    "param2": {"type": "integer", "description": "Second parameter"}
                },
                "required": ["param1", "param2"]
            },

This server implementation allows DSPy agents to expose capabilities through MCP, making them consumable by MCP-compatible clients.

Gotcha

Agenspy is early-stage software with 74 GitHub stars and experimental features clearly marked in the codebase. The MultiProtocolAgent functionality, while architecturally sound, carries an “experimental” warning—expect rough edges in protocol implementation and error handling. Production deployments should stick to single-protocol agents until the multi-protocol layer matures.

Documentation is thin beyond the README examples. Critical details like protocol configuration options, error recovery patterns, and session management strategies are missing. The code samples in the README are incomplete in places—the server example cuts off mid-parameter definition, and connection patterns for MCP clients aren’t fully specified. You’ll need to read the source to understand how connections are established or how capability discovery works in edge cases. If you need hand-holding, this isn’t ready. The project assumes you’re comfortable reading Python source and experimenting.

Agenspy also inherits DSPy’s learning curve. If you’re not already familiar with DSPy’s module composition model, its optimization loops, and its Prediction interface, you’ll be learning two frameworks simultaneously. For teams new to DSPy, starting with vanilla DSPy before adding Agenspy’s protocol layer makes more sense than diving straight into protocol-first architecture.

Verdict

Use Agenspy if you’re building DSPy agents that need to communicate via standardized protocols like MCP or Agent2Agent, especially if you want your agents discoverable in protocol directories like Google’s A2A registry. It’s ideal for teams already invested in DSPy’s optimization paradigm who need interoperability with multi-protocol agent ecosystems. The protocol-first architecture appears promising when you’re integrating with enterprise systems that expose capabilities through MCP or when building agent marketplaces where protocol standardization matters more than framework lock-in. Skip it if you’re starting fresh with agent frameworks—LangChain and LlamaIndex offer more mature ecosystems with better documentation and larger communities. Also skip if you need production-grade stability today; Agenspy’s experimental features and sparse documentation make it better suited for prototypes and proof-of-concepts than mission-critical deployments. Finally, if you don’t actually need protocol-based communication, vanilla DSPy with custom tool adapters will be simpler and more stable.

// ADD TO YOUR README
[![Featured on Starlog](https://starlog.is/api/badge/ai-agents/superagenticai-agenspy.svg)](https://starlog.is/api/badge-click/ai-agents/superagenticai-agenspy)