本仓库展示了如何借助 LlamaCloud 创建 MCP 服务器,以及如何将 LlamaIndex 用作 MCP 客户端。通过这些操作,你可以利用 RAG(检索增强生成)为 Claude 等客户端提供实时私人信息,以更精准地回答问题。
.env 文件并添加两个环境变量:
LLAMA_CLOUD_API_KEY - 上一步获取的 API 密钥。OPENAI_API_KEY - 您的 OpenAI API 密钥。运行以下命令以启动 MCP 服务器:
uvicorn mcp_server:app --reload
在 mcp_http_server.py 中,您可以找到以下代码:
from fastapi import FastAPI
import asyncio
from mcp_core.mcp_client import BasicMCPClient
from mcp_core.tool_spec import McpToolSpec
from langchain.agents import FunctionAgent
from langchain.llms import OpenAI
mcp = FastAPI(title="LlamaIndex MCP 服务器")
async def main():
await mcp.startup()
asyncio.create_task(mcp.run_sse_async())
if __name__ == "__main__":
asyncio.run(main())
mcp_client = BasicMCPClient("http://localhost:8000/sse")
mcp_tool_spec = McpToolSpec(
client=mcp_client,
allowed_tools=["tool1", "tool2"],
)
tools = mcp_tool_spec.to_tool_list()
llm = OpenAI(model="gpt-4o-mini")
agent = FunctionAgent(
tools=tools,
llm=llm,
system_prompt="您是一个知道如何在 LlamaIndex 中构建代理的智能体。",
)
async def run_agent():
response = await agent.run("如何在 LlamaIndex 中创建一个代理?")
print(response)
if __name__ == "__main__":
asyncio.run(run_agent())
你已完成所有设置!现在可以使用代理从您的 LlamaCloud 索引中获取信息了。