Back to MCP directory
publicPublicdnsLocal runtime

LlamaIndex Documentation

该项目展示了如何使用LlamaCloud创建MCP服务器及LlamaIndex作为MCP客户端的应用。

article

README

🚀 LlamaIndex MCP 演示

本仓库展示了如何借助 LlamaCloud 创建 MCP 服务器,以及如何将 LlamaIndex 用作 MCP 客户端。通过这些操作,你可以利用 RAG(检索增强生成)为 Claude 等客户端提供实时私人信息,以更精准地回答问题。

🚀 快速开始

✨ 使用 LlamaCloud 作为 MCP 服务器

📦 安装指南

设置您的 LlamaCloud 索引
  1. 获取 LlamaCloud 账户。
  2. 在 UI 中创建一个新的索引,并选择任意数据源。在此示例中,我们使用了 Google Drive 并提供了一部分 LlamaIndex 文档作为数据源。若仅用于测试,也可直接上传文档到索引。
  3. LlamaCloud UI 获取一个 API 密钥。
设置您的 MCP 服务器
  1. 克隆此仓库。
  2. 创建一个 .env 文件并添加两个环境变量:
    • LLAMA_CLOUD_API_KEY - 上一步获取的 API 密钥。
    • OPENAI_API_KEY - 您的 OpenAI API 密钥。

💻 使用示例

运行 MCP 服务器

运行以下命令以启动 MCP 服务器:

uvicorn mcp_server:app --reload

✨ 使用 LlamaIndex 作为 MCP 客户端

💻 使用示例

基础用法

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 索引中获取信息了。

help

Runtime guide

cloud

Hosted runtime

Hosted servers run from a provider-managed environment. You usually connect the MCP client to the hosted endpoint or follow the provider's authorization flow, without keeping a local process alive

  1. Open provider connection page
  2. Authorize or copy endpoint
  3. Connect from your MCP client
terminal

Local runtime / other methods

Local servers run on your own machine or infrastructure. You normally copy the server_config into your MCP client, install the required package, and provide env variables from env_schema when needed

  1. Copy server_config
  2. Install required package
  3. Fill env variables and restart client