> For the complete documentation index, see [llms.txt](https://doc.thordata.com/doc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.thordata.com/doc/zh/pa-qu/serp-api/ji-cheng/mcp-ji-cheng/langchain-ji-cheng.md).

# LangChain集成

将 Thordata MCP Server 连接到 LangChain 和 LangGraph Agent，以使用实时网页搜索、抓取、结构化数据工具并监控用量。

将 LangChain 和 LangGraph 代理连接到 ThorData MCP 伺服器，即可将即时网路搜寻、抓取和结构化数据工具添加至您的 AI 工作流程。

**托管 MCP**

{% stepper %}
{% step %}
**获取您的 API 令牌**

* 前往 [**ThorData SERP API - API Token**](https://dashboard.thordata.com/?request_time=1789527087547) 创建 API Token；
* 复制您的 API 令牌（格式如下：`sk_7qBRe***************************`）
  {% endstep %}

{% step %}
**安装所需软件包**

```
pip install langchain-mcp-adapters
```

{% endstep %}

{% step %}
**配置您的 MCP 服务器**

```
import asyncio
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain_mcp_adapters.client import MultiServerMCPClient
from dotenv import load_dotenv
import os

load_dotenv()

async def main():
# Configure MCP client
client = MultiServerMCPClient({
"thor_data": {
"url": "https://mcp.thordata.net/<API_TOKEN>/mcp",
"transport": "http",
}
})

# Get available tools
tools = await client.get_tools()
print("Available tools:", [tool.name for tool in tools])

# Configure LLM
llm = ChatOpenAI(
openai_api_key=os.getenv("OPENROUTER_API_KEY"),
openai_api_base="https://openrouter.ai/api/v1",
model_name="moonshotai/kimi-k2"
)

# System prompt for web search agent
system_prompt = """
You are a web search agent with comprehensive scraping capabilities. Your tools include:
- **search_engine**: Get search results from Google/Bing/Yandex
- **scrape_as_markdown**: Extract content from any webpage with bot detection bypass
- **Structured extractors**: Fast, reliable data from major platforms (Amazon, LinkedIn, Instagram, Facebook, X, TikTok, YouTube, Reddit, Zillow, etc.)
- **Browser automation**: Navigate, click, type, screenshot for complex interactions

Guidelines:
- Use structured web_data_* tools for supported platforms when possible (faster/more reliable)
- Use general scraping for other sites
- Handle errors gracefully and respect rate limits
- Think step by step about what information you need and which tools to use
- Be thorough in your research and provide comprehensive answers

When responding, follow this pattern:
1. Think about what information is needed
2. Choose the appropriate tool(s)
3. Execute the tool(s)
4. Analyze the results
5. Provide a clear, comprehensive answer
"""

# Create ReAct agent
agent = create_agent(
model=llm,
tools=tools,
system_prompt=system_prompt
)

# Test the agent
print("Testing ReAct Agent with available tools...")
print("=" * 50)

result = await agent.ainvoke({
"messages": [("human", "Search for the latest news about AI developments")]
})

print("\nAgent Response:")
print(result["messages"][-1].content)

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

{% endstep %}

{% step %}
**设定环境变量**

`.env`在项目目录中创建一个文件：

```
OPENROUTER_API_KEY=your_openrouter_api_key_here
```

{% endstep %}

{% step %}
**测试一下是否有效**

* 请替换<kbd>\<API\_TOKEN></kbd>为您的实际ThorData API令牌
* 运行你的LangChain脚本
* 你应该看到 agent 执行网络搜寻并提供全面的回复。
  {% endstep %}

{% step %}
**监控使用情况**

* 在 ThorData SERP API-[**使用记录**](https://dashboard.thordata.com/?request_time=1789527087547)中查看您的 API 使用情况。
  {% endstep %}
  {% endstepper %}

如需更多协助，请透过 **线上客服** 或电邮 [**support@thordata.com**](mailto:support@thordata.com) 联络我们。
