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

dw制作一个环保网站模板下载官方网站建设怎么样

dw制作一个环保网站模板下载,官方网站建设怎么样,wordpress 页面内菜单,6个常用项目管理软件文章目录 下载Traeuv 工具教程参考我的这篇文章创建 uv 项目main.pyTrae 配置 MCP 服务添加 MCP创建智能体 使用智能体调用 MCP 创建 demo 表查询 demo 表结构信息demo 表插入 2 条测试数据查询 demo 表中的数据 下载Trae https://www.trae.com.cn/ uv 工具教程参考我的这篇…

文章目录

  • 下载Trae
  • uv 工具教程参考我的这篇文章
  • 创建 uv 项目
  • main.py
  • Trae 配置 MCP 服务
    • 添加 MCP
    • 创建智能体
  • 使用智能体
    • 调用 MCP 创建 demo 表
    • 查询 demo 表结构信息
    • demo 表插入 2 条测试数据
    • 查询 demo 表中的数据

下载Trae

  • https://www.trae.com.cn/
    在这里插入图片描述

uv 工具教程参考我的这篇文章

  • 让 Python 项目管理变简单(uv 工具快速上手指南)

创建 uv 项目

uv init demo
cd demo
  • 添加依赖项
uv add 'mcp[cli]'

在这里插入图片描述

main.py

import asyncio
import argparse
import sqlite3
import logging
from contextlib import closing
from pathlib import Path
from pydantic import AnyUrl
from typing import Anyfrom mcp.server import InitializationOptions
from mcp.server.lowlevel import Server, NotificationOptions
from mcp.server.stdio import stdio_server
import mcp.types as typeslogger = logging.getLogger('mcp_sqlite_server')
logger.info("Starting MCP SQLite Server")class SqliteDatabase:def __init__(self, db_path: str):self.db_path = str(Path(db_path).expanduser())Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)self._init_database()self.insights: list[str] = []def _init_database(self):"""Initialize connection to the SQLite database"""logger.debug("Initializing database connection")with closing(sqlite3.connect(self.db_path)) as conn:conn.row_factory = sqlite3.Rowconn.close()def _synthesize_memo(self) -> str:"""Synthesizes business insights into a formatted memo"""logger.debug(f"Synthesizing memo with {len(self.insights)} insights")if not self.insights:return "No business insights have been discovered yet."insights = "\n".join(f"- {insight}" for insight in self.insights)memo = "📊 Business Intelligence Memo 📊\n\n"memo += "Key Insights Discovered:\n\n"memo += insightsif len(self.insights) > 1:memo += "\nSummary:\n"memo += f"Analysis has revealed {len(self.insights)} key business insights that suggest opportunities for strategic optimization and growth."logger.debug("Generated basic memo format")return memodef _execute_query(self, query: str, params: dict[str, Any] | None = None) -> list[dict[str, Any]]:"""Execute a SQL query and return results as a list of dictionaries"""logger.debug(f"Executing query: {query}")try:with closing(sqlite3.connect(self.db_path)) as conn:conn.row_factory = sqlite3.Rowwith closing(conn.cursor()) as cursor:if params:cursor.execute(query, params)else:cursor.execute(query)if query.strip().upper().startswith(('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER')):conn.commit()affected = cursor.rowcountlogger.debug(f"Write query affected {affected} rows")return [{"affected_rows": affected}]results = [dict(row) for row in cursor.fetchall()]logger.debug(f"Read query returned {len(results)} rows")return resultsexcept Exception as e:logger.error(f"Database error executing query: {e}")raiseasync def main(db_path: str):logger.info(f"Starting SQLite MCP Server with DB path: {db_path}")db = SqliteDatabase(db_path)server = Server("sqlite-manager")logger.debug("Registering handlers")@server.list_resources()async def handle_list_resources() -> list[types.Resource]:logger.debug("Handling list_resources request")return [types.Resource(uri=AnyUrl("memo://insights"),name="Business Insights Memo",description="A living document of discovered business insights",mimeType="text/plain",)]@server.read_resource()async def handle_read_resource(uri: AnyUrl) -> str:logger.debug(f"Handling read_resource request for URI: {uri}")if uri.scheme != "memo":logger.error(f"Unsupported URI scheme: {uri.scheme}")raise ValueError(f"Unsupported URI scheme: {uri.scheme}")path = str(uri).replace("memo://", "")if not path or path != "insights":logger.error(f"Unknown resource path: {path}")raise ValueError(f"Unknown resource path: {path}")return db._synthesize_memo()@server.list_tools()async def handle_list_tools() -> list[types.Tool]:"""List available tools"""return [types.Tool(name="read_query",description="Execute a SELECT query on the SQLite database",inputSchema={"type": "object","properties": {"query": {"type": "string", "description": "SELECT SQL query to execute"},},"required": ["query"],},),types.Tool(name="write_query",description="Execute an INSERT, UPDATE, or DELETE query on the SQLite database",inputSchema={"type": "object","properties": {"query": {"type": "string", "description": "SQL query to execute"},},"required": ["query"],},),types.Tool(name="create_table",description="Create a new table in the SQLite database",inputSchema={"type": "object","properties": {"query": {"type": "string", "description": "CREATE TABLE SQL statement"},},"required": ["query"],},),types.Tool(name="list_tables",description="List all tables in the SQLite database",inputSchema={"type": "object","properties": {},},),types.Tool(name="describe_table",description="Get the schema information for a specific table",inputSchema={"type": "object","properties": {"table_name": {"type": "string", "description": "Name of the table to describe"},},"required": ["table_name"],},),types.Tool(name="append_insight",description="Add a business insight to the memo",inputSchema={"type": "object","properties": {"insight": {"type": "string", "description": "Business insight discovered from data analysis"},},"required": ["insight"],},),]@server.call_tool()async def handle_call_tool(name: str, arguments: dict[str, Any] | None) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:"""Handle tool execution requests"""try:if name == "list_tables":results = db._execute_query("SELECT name FROM sqlite_master WHERE type='table'")return [types.TextContent(type="text", text=str(results))]elif name == "describe_table":if not arguments or "table_name" not in arguments:raise ValueError("Missing table_name argument")results = db._execute_query(f"PRAGMA table_info({arguments['table_name']})")return [types.TextContent(type="text", text=str(results))]elif name == "append_insight":if not arguments or "insight" not in arguments:raise ValueError("Missing insight argument")db.insights.append(arguments["insight"])_ = db._synthesize_memo()# Notify clients that the memo resource has changedawait server.request_context.session.send_resource_updated(AnyUrl("memo://insights"))return [types.TextContent(type="text", text="Insight added to memo")]if not arguments:raise ValueError("Missing arguments")if name == "read_query":if not arguments["query"].strip().upper().startswith("SELECT"):raise ValueError("Only SELECT queries are allowed for read_query")results = db._execute_query(arguments["query"])return [types.TextContent(type="text", text=str(results))]elif name == "write_query":if arguments["query"].strip().upper().startswith("SELECT"):raise ValueError("SELECT queries are not allowed for write_query")results = db._execute_query(arguments["query"])return [types.TextContent(type="text", text=str(results))]elif name == "create_table":if not arguments["query"].strip().upper().startswith("CREATE TABLE"):raise ValueError("Only CREATE TABLE statements are allowed")db._execute_query(arguments["query"])return [types.TextContent(type="text", text="Table created successfully")]else:raise ValueError(f"Unknown tool: {name}")except sqlite3.Error as e:return [types.TextContent(type="text", text=f"Database error: {str(e)}")]except Exception as e:return [types.TextContent(type="text", text=f"Error: {str(e)}")]async with stdio_server() as (read_stream, write_stream):logger.info("Server running with stdio transport")await server.run(read_stream,write_stream,InitializationOptions(server_name="sqlite",server_version="0.1.0",capabilities=server.get_capabilities(notification_options=NotificationOptions(),experimental_capabilities={},),),)if __name__ == "__main__":parser = argparse.ArgumentParser(description='SQLite MCP Server')parser.add_argument('--db-path', default="./sqlite_mcp_server.db", help='Path to SQLite database file')args = parser.parse_args()asyncio.run(main(args.db_path))

Trae 配置 MCP 服务

  • 下载Trae:https://www.trae.com.cn/

添加 MCP

{"mcpServers": {"sqlite-server": {"command": "uv","args": ["--directory","~/TraeProjects/demo","run","main.py","--db-path","~/TraeProjects/demo/test.db"]}}
}

在这里插入图片描述
在这里插入图片描述

创建智能体

在这里插入图片描述

使用智能体

调用 MCP 创建 demo 表

在这里插入图片描述

查询 demo 表结构信息

在这里插入图片描述

demo 表插入 2 条测试数据

在这里插入图片描述

查询 demo 表中的数据

在这里插入图片描述


文章转载自:

http://m8yLBebU.cmzgt.cn
http://9EJGrkiA.cmzgt.cn
http://7f4HGfFk.cmzgt.cn
http://UAVo9bCB.cmzgt.cn
http://A9Vb7eId.cmzgt.cn
http://0Eaelv1f.cmzgt.cn
http://aIMwgaq0.cmzgt.cn
http://i1dqOUuO.cmzgt.cn
http://uHB8JbMZ.cmzgt.cn
http://7nuDSI4F.cmzgt.cn
http://TdpDj64H.cmzgt.cn
http://eEHIEe3l.cmzgt.cn
http://giZlvRTA.cmzgt.cn
http://y8LYd59z.cmzgt.cn
http://IeIJlh4N.cmzgt.cn
http://iOXyVhUk.cmzgt.cn
http://TRGWHOuQ.cmzgt.cn
http://T4FGVfwk.cmzgt.cn
http://bZHxhYzT.cmzgt.cn
http://0FYgliox.cmzgt.cn
http://Ki5Fa6Y4.cmzgt.cn
http://cjKayQd2.cmzgt.cn
http://X4MVC9k4.cmzgt.cn
http://z9HFiTB4.cmzgt.cn
http://G11zMVKd.cmzgt.cn
http://SNLMIjND.cmzgt.cn
http://vltEiM2e.cmzgt.cn
http://F9xZLgrg.cmzgt.cn
http://9ZjO31wG.cmzgt.cn
http://Ow5pr1IO.cmzgt.cn
http://www.dtcms.com/wzjs/654655.html

相关文章:

  • 有域名了也备案了怎么做网站阴阳师网站建设
  • wap网站设计规范福建省建设厅网站官网
  • 服装型网站开发怎么做卖东西的网站
  • 网站建设策划实训总结国外设计网站大全
  • 如何设计网站建设方案广告设计公司招聘
  • 建设网站如何优化关键词商丘市网站建设公司
  • 做试用的网站有域名如何做免费网站
  • 微信知彼网络网站建设中铁建设集团招聘信息
  • 上海电子商务网站制作小榄网站设计
  • 湖州网站建设官网wordpress插件用户权限
  • 茶叶网站建设方案ai时代模版价格
  • 汕头网站建设浩森宇特个人免费发布招聘信息
  • 怎么用VS2012建设网站四川建设网招标网
  • 有自建服务器做网站的吗科普重庆网站
  • 如何做网站淘宝客网站建设推广接单语
  • 做淘宝还是做网站容易自己做网站什么网站比较好
  • 电商网站开发文献综述阿里云企业网站建设
  • 光泽网站建设wzjseo平面设计找素材的网站
  • wordpress怎么把分类弄在左边已收录的网站不好优化
  • 网站到期怎么续费盗版小说网站怎么做
  • 简单的j网站建设方案书付款网站源码
  • wordpress的ftp设置北京seo诊断
  • 个人备案的网站涉及到资金爱网站免费一站二站
  • 网站服务器时间查询工具最新军事新闻新浪网
  • 万能站工具的企业网站系统无锡网站seo
  • 南昌网站设计公司哪家好网站建设维护有哪些内容
  • 有哪些好的网站项目网络服务商不提供哪项服务
  • 商业网站有什么作用建设网站如何优化关键词
  • 域名购买哪个网站最好电子商务网站开发书例子
  • 推广网站大全呼和浩特网站建设