|
| 1 | +""" |
| 2 | +Use an LLM to query a database in human language via MCP. |
| 3 | +Example code using LlamaIndex with vanilla Open AI and Azure Open AI. |
| 4 | +
|
| 5 | +https://github.com/run-llama/llama_index/tree/main/llama-index-integrations/tools/llama-index-tools-mcp |
| 6 | +
|
| 7 | +## Start CrateDB MCP Server |
| 8 | +``` |
| 9 | +export CRATEDB_CLUSTER_URL="http://localhost:4200/" |
| 10 | +cratedb-mcp serve --transport=streamable-http |
| 11 | +``` |
| 12 | +
|
| 13 | +## Usage |
| 14 | +``` |
| 15 | +source env.standalone |
| 16 | +export OPENAI_API_KEY=sk-XJZ7pfog5Gp8Kus8D--invalid--0CJ5lyAKSefZLaV1Y9S1 |
| 17 | +python demo_mcp.py |
| 18 | +``` |
| 19 | +""" |
| 20 | +import asyncio |
| 21 | +from cratedb_about.instruction import Instructions |
| 22 | + |
| 23 | +from dotenv import load_dotenv |
| 24 | +from llama_index.core.agent.workflow import FunctionAgent |
| 25 | +from llama_index.llms.openai import OpenAI |
| 26 | +from llama_index.tools.mcp import BasicMCPClient, McpToolSpec |
| 27 | + |
| 28 | +from boot import configure_llm |
| 29 | + |
| 30 | + |
| 31 | +class Agent: |
| 32 | + |
| 33 | + async def get_tools(self): |
| 34 | + # Connect to the CrateDB MCP server using `streamable-http` transport. |
| 35 | + mcp_client = BasicMCPClient("http://127.0.0.1:8000/mcp/") |
| 36 | + mcp_tool_spec = McpToolSpec( |
| 37 | + client=mcp_client, |
| 38 | + # Optional: Filter the tools by name |
| 39 | + # allowed_tools=["tool1", "tool2"], |
| 40 | + # Optional: Include resources in the tool list |
| 41 | + # include_resources=True, |
| 42 | + ) |
| 43 | + return await mcp_tool_spec.to_tool_list_async() |
| 44 | + |
| 45 | + async def get_agent(self): |
| 46 | + return FunctionAgent( |
| 47 | + name="Agent", |
| 48 | + description="CrateDB text-to-SQL agent", |
| 49 | + llm=OpenAI(model="gpt-4o"), |
| 50 | + tools=await self.get_tools(), |
| 51 | + system_prompt=Instructions.full(), |
| 52 | + ) |
| 53 | + |
| 54 | + async def aquery(self, query): |
| 55 | + return await (await self.get_agent()).run(query) |
| 56 | + |
| 57 | + def query(self, query): |
| 58 | + return asyncio.run(self.aquery(query)) |
| 59 | + |
| 60 | + |
| 61 | +def main(): |
| 62 | + """ |
| 63 | + Use an LLM to query a database in human language. |
| 64 | + """ |
| 65 | + |
| 66 | + # Configure application. |
| 67 | + load_dotenv() |
| 68 | + configure_llm() |
| 69 | + |
| 70 | + # Use an agent that uses the CrateDB MCP server. |
| 71 | + agent = Agent() |
| 72 | + |
| 73 | + # Invoke an inquiry. |
| 74 | + print("Running query") |
| 75 | + QUERY_STR = "What is the average value for sensor 1?" |
| 76 | + answer = agent.query(QUERY_STR) |
| 77 | + print("Query was:", QUERY_STR) |
| 78 | + print("Answer was:", answer) |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + main() |
0 commit comments