如何将Flask与MCP AI Agent结合构建生成器?

摘要:前言 近年来,大量新兴的 AI 相关第三方库都提供了异步接口,有些甚至出于性能考虑仅支持异步调用,例如 MCP SDK。伴随着 Python 异步编程的发展,FastAPI 等框架迅速流行,许多新项目倾向于采用 FastAPI。但实际上,F
前言 近年来,大量新兴的 AI 相关第三方库都提供了异步接口,有些甚至出于性能考虑仅支持异步调用,例如 MCP SDK。伴随着 Python 异步编程的发展,FastAPI 等框架迅速流行,许多新项目倾向于采用 FastAPI。但实际上,Flask 自 2.0 版本起也开始支持异步方法,因此我们也能借助 Flask 参与到 MCP 的 AI Agent 浪潮中。 PS:需要注意的是,Flask 的异步性能表现不佳。正如 Flask 官方文档所指出的那样,每当收到请求时,Flask 都会在一个线程内启动一个新的事件循环来执行异步视图函数,然后返回结果。这种方式增加了额外的性能开销。经过个人实测,Flask 的异步视图性能确实不如传统的同步视图。因此,如果有异步需求,建议还是选用像 FastAPI 这样原生支持异步的框架。 Async functions require an event loop to run. Flask, as a WSGI application, uses one worker to handle one request/response cycle. When a request comes in to an async view, Flask will start an event loop in a thread, run the view function there, then return the result. Each request still ties up one worker, even for async views. The upside is that you can run async code within a view, for example to make multiple concurrent database queries, HTTP requests to an external API, etc. However, the number of requests your application can handle at one time will remain the same. Async is not inherently faster than sync code. Async is beneficial when performing concurrent IO-bound tasks, but will probably not improve CPU-bound tasks. Traditional Flask views will still be appropriate for most use cases, but Flask's async support enables writing and using code that wasn't possible natively before. 本文使用的 LLM 是阿里的通义千问,需要自行申请 API Key。其他兼容 OpenAI SDK 的模型理论上也可使用。 本文介绍的是如何在 Flask 中集成基于 MCP Client 和 MCP Server 的 AI Agent,并不仅仅是用 Flask 开发一个 MCP Server,所以只关注 Flask 实现 MCP Server 的看众可以关闭本文了。 安装 SDK 虽然 Flask 从 2.0 版本开始支持异步功能,但这部分功能需要额外安装相关依赖。这里我们将 MCP 和 LLM 相关的依赖一起安装。 uv add 'flask[async]' fastmcp openai 此外还需要安装 gunicorn 和 gevent,这两个是在生产环境中常用的部署工具。虽然是开发演示项目,但我们也会安装它们来验证异步功能的支持情况。 uv add gunicorn gevent 代码示例 代码结构 由于这只是个演示项目,所以代码结构相对简单。
阅读全文