| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- """
- FastAPI HTTP 代理服务
- 代理 HTTP://192.168.0.42:8005/mcp 接口
- """
- import httpx
- from fastapi import FastAPI, Request, Response
- from fastapi.responses import StreamingResponse
- import json
- app = FastAPI(
- title="HTTP Proxy Service",
- description="代理 MCP 接口到 192.168.0.42:8005",
- version="1.0.0"
- )
- # 目标服务地址
- TARGET_BASE_URL = "http://192.168.0.42:8005"
- def get_forwarded_headers(request: Request) -> dict:
- """获取需要转发的 headers"""
- headers = {}
- # 转发所有 headers,跳过一些不需要的
- skip_headers = {"host", "content-length", "transfer-encoding"}
-
- for key, value in request.headers.items():
- if key.lower() not in skip_headers:
- headers[key] = value
-
- return headers
- async def proxy_request(path: str, request: Request):
- """代理请求到目标服务"""
- url = f"{TARGET_BASE_URL}{path}"
- method = request.method
- headers = get_forwarded_headers(request)
-
- # 获取请求体
- body = await request.body()
-
- async with httpx.AsyncClient(timeout=60.0) as client:
- try:
- # 发送请求
- response = await client.request(
- method=method,
- url=url,
- headers=headers,
- content=body if body else None,
- params=request.query_params
- )
-
- # 构建响应头
- response_headers = {}
- for key, value in response.headers.items():
- if key.lower() not in {"content-length", "transfer-encoding", "connection"}:
- response_headers[key] = value
-
- # 返回响应
- return Response(
- content=response.content,
- status_code=response.status_code,
- headers=response_headers
- )
-
- except httpx.TimeoutException:
- return Response(
- content=json.dumps({"error": "请求超时"}).encode("utf-8"),
- status_code=504,
- media_type="application/json"
- )
- except httpx.ConnectError:
- return Response(
- content=json.dumps({"error": "无法连接到目标服务"}).encode("utf-8"),
- status_code=503,
- media_type="application/json"
- )
- except Exception as e:
- return Response(
- content=json.dumps({"error": f"代理请求失败: {str(e)}"}).encode("utf-8"),
- status_code=500,
- media_type="application/json"
- )
- @app.api_route("/mcp/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
- async def proxy_mcp(path: str, request: Request):
- """代理 /mcp 路径下的所有请求"""
- target_path = f"/mcp/{path}"
- return await proxy_request(target_path, request)
- @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
- async def proxy_all(path: str, request: Request):
- """代理所有其他路径的请求"""
- return await proxy_request(f"/{path}", request)
- if __name__ == "__main__":
- import uvicorn
- uvicorn.run("p04:app", host="0.0.0.0", port=8000, reload=True)
|