当前位置: 首页 > news >正文

Dify-MCP服务创建案例

直接上代码:

import mysql.connector
import json
import os
import requests
from contextlib import contextmanager
from dotenv import load_dotenv
from fastmcp import FastMCP# 加载环境变量
load_dotenv()# 第三方API默认配置
DEFAULT_TIMEOUT = int(os.getenv("API_TIMEOUT", 10))  # 默认超时时间10秒
DEFAULT_HEADERS = {"Content-Type": "application/json","User-Agent": "FastMCP-Service/1.0"
}class DbManager:def __init__(self):self.connection_pool = mysql.connector.pooling.MySQLConnectionPool(pool_name="db_pool",pool_size=5,pool_reset_session=True,host=os.getenv("DB_HOST", "106.55.102.254"),port=os.getenv("DB_PORT", 3306),  # 添加端口配置user=os.getenv("DB_USER", "root"),password=os.getenv("DB_PASSWD", "dh123456"),database=os.getenv("DB_NAME", "test01"),connect_timeout=30,  # 连接超时设置charset='utf8mb4'    # 字符集设置)@contextmanagerdef get_cursor(self):with self.connection_pool.get_connection() as connection:cursor = Nonetry:cursor = connection.cursor()yield cursorconnection.commit()except Exception as e:connection.rollback()raise efinally:if cursor:cursor.close()def execute_sql(self, sql: str) -> str:with self.get_cursor() as cursor:cursor.execute(sql)if cursor.description is not None:rows = cursor.fetchall()result = {"columns": [desc[0] for desc in cursor.description],"rows": rows,}return json.dumps(result, default=str)else:return f"row affected:{cursor.rowcount}"class ThirdPartyAPIManager:"""第三方接口请求管理器"""@staticmethoddef request_api(url: str,method: str = "GET",params: dict = None,data: dict = None,headers: dict = None,timeout: int = None) -> str:"""通用的第三方API请求方法参数:url: 接口URL地址method: 请求方法,如GET、POST等params: URL查询参数data: 请求体数据headers: 请求头timeout: 超时时间,秒返回:接口响应的JSON字符串"""try:# 处理默认参数timeout = timeout or DEFAULT_TIMEOUTrequest_headers = DEFAULT_HEADERS.copy()# 合并自定义请求头if headers:request_headers.update(headers)# 处理请求数据kwargs = {"url": url,"headers": request_headers,"timeout": timeout,"params": params or {}}# 根据请求方法处理数据method = method.upper()if method in ["POST", "PUT", "PATCH"]:kwargs["json"] = data or {}  # 使用json参数自动处理Content-Type# 发送请求response = requests.request(method, **kwargs)# 检查响应状态码response.raise_for_status()# 尝试解析JSON响应try:result = {"status": "success","status_code": response.status_code,"data": response.json()}except json.JSONDecodeError:# 非JSON响应result = {"status": "success","status_code": response.status_code,"data": response.text,"message": "Response is not JSON format"}return json.dumps(result, default=str)except requests.exceptions.RequestException as e:# 处理请求异常error_info = {"status": "error","message": str(e),"type": type(e).__name__}return json.dumps(error_info, default=str)except Exception as e:# 处理其他异常error_info = {"status": "error","message": f"Unexpected error: {str(e)}"}return json.dumps(error_info, default=str)# 初始化实例
dbManager = DbManager()
apiManager = ThirdPartyAPIManager()# 初始化FastMCP服务器
mcp = FastMCP(name="查询Mysql服务")@mcp.tool(description="查询表结构")
def get_table_definition(table: str) -> str:"""get table definition"""return dbManager.execute_sql(f"show create table {table}")@mcp.tool(description="执行SQL语句")
def execute_sql(sql: str) -> str:"""execute sql"""return dbManager.execute_sql(sql)@mcp.tool(description="请求第三方API接口,支持GET、POST等方法")
def request_third_party_api(url: str,method: str = "GET",params: dict = None,data: dict = None,headers: dict = None,timeout: int = None
) -> str:"""请求第三方API接口参数:url: 必须,API接口的URL地址method: 可选,请求方法,默认为GET,可选项包括GET、POST、PUT、DELETE等params: 可选,URL查询参数,字典类型data: 可选,请求体数据,字典类型,用于POST、PUT等方法headers: 可选,请求头信息,字典类型timeout: 可选,超时时间,单位秒返回:接口响应结果的JSON字符串"""return apiManager.request_api(url=url,method=method,params=params,data=data,headers=headers,timeout=timeout)if __name__ == "__main__":# 使用SSE传输mcp.run(transport="sse", host="0.0.0.0", port=8520)

启动:
python3 my_mcp_01.py
在这里插入图片描述

http://www.dtcms.com/a/339184.html

相关文章:

  • 循环高级综合练习①
  • 46 C++ STL模板库15-容器7-顺序容器-双端队列(deque)
  • 人工智能统一信息结构的挑战与前景
  • Vue3编程中更多常见书写错误场景
  • 使用OpenCV计算灰度图像的质心
  • 云原生堡垒机渗透测试场景
  • 所有普通I/O口都支持中断的51单片机@Ai8051U, AiCube 图形化配置
  • 微服务架构的演进:从 Spring Cloud Netflix 到云原生新生态
  • 大模型微调RAG、LORA、强化学习
  • 如何使用VNC对openEuler系统进行远程图形化操作
  • Ubuntu Server 22.04 k8s部署服务较时,文件描述符超过限制的处理方法
  • RabbitMQ:SpringBoot+RabbitMQ 多消费者绑定同一队列
  • Node.js 在 Windows Server 上的离线部署方案
  • leetcode349. 两个数组的交集
  • 轻度娱乐浪潮下定制开发开源AI智能名片S2B2C商城小程序的机遇与策略
  • 厚板数控矫平机的“第三堂课”——把视角拉远,看看它如何重塑整条制造链
  • 供水设备智慧化管理物联网解决方案:远程监控与运维
  • 搭建最新--若依分布式spring cloudv3.6.6 前后端分离项目--步骤与记录常见的坑
  • BKP相关知识点
  • 从机器视觉到图像识别:计算机视觉的多维探索
  • LINUX819 shell:for for,shift ,{} ,array[0] array[s] ,declare -x -a
  • 服务注册与服务发现原理与实现
  • CentOS 8开发测试环境:直接安装还是Docker更优?
  • Docker核心---数据卷(堵门秘籍)
  • 应用控制技术、内容审计技术、AAA服务器技术
  • 深入理解Redis持久化:让你的数据永不丢失
  • 电子电气架构 ---SDV技术基础与传统E/E架构有何不同?
  • 利用图数据库高效解决 Text2sql 任务中表结构复杂时占用过多大模型上下文的问题
  • 智慧养老中IPTV融合对讲:重塑养老沟通新生态
  • t12 low power design: power plan脚本分享(4) power stripe