DSPy Integration

async agentstr.mcp.dspy.to_dspy_tools(nostr_mcp_client: NostrMCPClient) list[Tool][source]

Convert tools from the MCP client to Dspy tools.

Parameters:

nostr_mcp_client – An instance of NostrMCPClient to fetch tools from.

Returns:

A list of DSPy Tool objects that wrap the MCP tools.

This module provides integration with DSPy tools, enabling conversion between MCP tools and DSPy’s tool format.

Usage Example

 1from dotenv import load_dotenv
 2
 3load_dotenv()
 4
 5import os
 6
 7import dspy
 8
 9from agentstr import NostrAgentServer, NostrMCPClient, ChatInput
10from agentstr.mcp.dspy import to_dspy_tools
11
12# Create Nostr MCP client
13nostr_mcp_client = NostrMCPClient(relays=os.getenv("NOSTR_RELAYS").split(","),
14                                  private_key=os.getenv("EXAMPLE_DSPY_AGENT_NSEC"),
15                                  mcp_pubkey=os.getenv("EXAMPLE_MCP_SERVER_PUBKEY"),
16                                  nwc_str=os.getenv("MCP_CLIENT_NWC_CONN_STR"))
17
18async def agent_server():    
19    # Convert tools to DSPy tools
20    dspy_tools = await to_dspy_tools(nostr_mcp_client)
21
22    for tool in dspy_tools:
23        print(f'Found {tool.name}: {tool.desc}')
24
25    # Create ReAct agent
26    react = dspy.ReAct("question -> answer: str", tools=dspy_tools)
27
28    # Configure DSPy
29    dspy.configure(lm=dspy.LM(model=os.getenv("LLM_MODEL_NAME"), 
30                              api_base=os.getenv("LLM_BASE_URL").rstrip("/v1"), 
31                              api_key=os.getenv("LLM_API_KEY"), 
32                              model_type="chat",
33                              temperature=0))
34
35    # Define agent callable
36    async def agent_callable(chat_input: ChatInput) -> str:
37        return (await react.acall(question=chat_input.messages[-1])).answer
38
39    # Create Nostr Agent Server
40    server = NostrAgentServer(nostr_mcp_client=nostr_mcp_client,
41                              agent_callable=agent_callable)
42
43    # Start server
44    await server.start()
45
46
47if __name__ == "__main__":
48    import asyncio
49    asyncio.run(agent_server())