利希尔 MCP
MCP(模型上下文协议)集成 李希尔 框架。
此软件包使Lihil应用程序能够将其端点作为MCP工具和资源公开,允许它们被兼容MCP的客户端(如Claude Code)使用。
安装
pip install lihil-mcp或者使用紫外线:
uv add lihil-mcp快速开始
基本用法
from lihil import Lihil
from lihil_mcp import MCPConfig
# Create your Lihil app
app = Lihil()
# Enable MCP with auto-exposure
mcp_config = MCPConfig(enabled=True, auto_expose=True)
app.enable_mcp(mcp_config)
# Your endpoints are automatically exposed as MCP tools/resources
@app.sub("/users/{user_id}")get
async def get_user(user_id: int) -> dict:
return {"id": user_id, "name": "User"}
@app.sub("/send-email").post
async def send_email(to: str, subject: str, body: str) -> str:
return f"Email sent to {to}"手动MCP装饰
from lihil import Lihil
from lihil_mcp import MCPConfig, mcp_tool, mcp_resource
app = Lihil()
mcp_config = MCPConfig(enabled=True, auto_expose=False)
app.enable_mcp(mcp_config)
# Explicitly mark endpoints as MCP tools
@app.sub("/send-email").post
@mcp_tool(title="Send Email", description="Send an email to a recipient")
async def send_email(to: str, subject: str, body: str) -> str:
# Email sending logic
return f"Email sent to {to}"
# Explicitly mark endpoints as MCP resources
@app.sub("/users/{user_id}").get
@mcp_resource("users://{user_id}", title="User Profile", description="Get user profile")
async def get_user(user_id: int) -> dict:
return {"id": user_id, "name": "User"}配置
MCPConfig选项
from lihil_mcp import MCPConfig
config = MCPConfig(
enabled=True, # Enable MCP functionality
server_name="my-api-server", # Name of the MCP server
auto_expose=True, # Auto-expose all endpoints as MCP tools/resources
expose_docs=True, # Expose OpenAPI docs as MCP resources
auth_required=False, # Whether authentication is required
transport="asgi", # Transport protocol ("asgi" or "stdio")
mcp_path_prefix="/mcp" # URL path prefix for MCP endpoints
)运作原理
自动曝光模式
当 auto_expose=True:
- GET端点 -作为MCP资源公开
- POST/PUT/PATCH端点 -暴露为MCP工具
手工装饰
使用装饰器进行细粒度控制:
@mcp_tool()-将端点标记为MCP工具@mcp_resource()-将端点标记为MCP资源
运输
该包使用ASGI传输在同一服务器上处理常规HTTP请求和MCP协议请求。
与Lihil功能集成
认证
利用Lihil的认证插件:
from lihil_mcp import MCPConfig
# Enable authentication for MCP operations
config = MCPConfig(enabled=True, auth_required=True)依赖注入
MCP与Lihil的依赖注入系统无缝协作:
from lihil import Lihil, Use
from lihil_mcp import mcp_tool
app = Lihil()
class EmailService:
def send(self, to: str, subject: str, body: str) -> str:
return f"Email sent to {to}"
@app.sub("/send-email").post
@mcp_tool(title="Send Email")
async def send_email(
to: str,
subject: str,
body: str,
email_service: Use[EmailService]
) -> str:
return email_service.send(to, subject, body)例子
请参阅 示例目录 查看完整的工作示例。
需求
- Python 3.10+
- lihil>=0.2.0
- mcp>=1.8.1
发展
# Clone the repository
git clone https://github.com/raceychan/lihil-mcp.git
cd lihil-mcp
# Install with development dependencies
uv sync --group dev
# Run tests
uv run pytest
# Run tests with coverage
uv run pytest --cov=lihil_mcp许可证
MIT许可证-请参阅 许可证 文件以获取详细信息。
贡献
欢迎投稿!请随时提交拉取请求。
