mirror of
https://github.com/FuQuan233/nonebot-plugin-llmchat.git
synced 2026-08-13 18:19:29 +00:00
Compare commits
No commits in common. "41e6aeacb9bf5f9e891919244b08e45b921790fb" and "38af060cb2e2a5e27e12988f8742a135347f8902" have entirely different histories.
41e6aeacb9
...
38af060cb2
6 changed files with 357 additions and 1094 deletions
14
README.md
14
README.md
|
|
@ -123,7 +123,6 @@ _✨ 支持多API预设、MCP协议、内置工具、联网搜索、视觉模型
|
||||||
| LLMCHAT__DEFAULT_PRESET | 否 | off | 默认使用的预设名称,配置为off则为关闭 |
|
| LLMCHAT__DEFAULT_PRESET | 否 | off | 默认使用的预设名称,配置为off则为关闭 |
|
||||||
| LLMCHAT__RANDOM_TRIGGER_PROB | 否 | 0.05 | 默认随机触发概率 [0, 1] |
|
| LLMCHAT__RANDOM_TRIGGER_PROB | 否 | 0.05 | 默认随机触发概率 [0, 1] |
|
||||||
| LLMCHAT__DEFAULT_PROMPT | 否 | 你的回答应该尽量简洁、幽默、可以使用一些语气词、颜文字。你应该拒绝回答任何政治相关的问题。 | 默认提示词 |
|
| LLMCHAT__DEFAULT_PROMPT | 否 | 你的回答应该尽量简洁、幽默、可以使用一些语气词、颜文字。你应该拒绝回答任何政治相关的问题。 | 默认提示词 |
|
||||||
| LLMCHAT__MCP_SERVER_CWD | 否 | 无 | command类型MCP服务器全局工作目录(cwd) |
|
|
||||||
| LLMCHAT__BLACKLIST_USER_IDS | 否 | [] | 黑名单用户ID列表,机器人将不会处理黑名单用户的消息 |
|
| LLMCHAT__BLACKLIST_USER_IDS | 否 | [] | 黑名单用户ID列表,机器人将不会处理黑名单用户的消息 |
|
||||||
| LLMCHAT__IGNORE_PREFIXES | 否 | [] | 需要忽略的消息前缀列表,匹配到这些前缀的消息不会处理 |
|
| LLMCHAT__IGNORE_PREFIXES | 否 | [] | 需要忽略的消息前缀列表,匹配到这些前缀的消息不会处理 |
|
||||||
| LLMCHAT__MCP_SERVERS | 否 | {} | MCP服务器配置,具体见下表 |
|
| LLMCHAT__MCP_SERVERS | 否 | {} | MCP服务器配置,具体见下表 |
|
||||||
|
|
@ -166,11 +165,10 @@ LLMCHAT__MCP_SERVERS同样为一个dict,key为服务器名称,value配置的
|
||||||
| 配置项 | 必填 | 默认值 | 说明 |
|
| 配置项 | 必填 | 默认值 | 说明 |
|
||||||
|:-----:|:----:|:----:|:----:|
|
|:-----:|:----:|:----:|:----:|
|
||||||
| command | stdio服务器必填 | 无 | stdio服务器MCP命令 |
|
| command | stdio服务器必填 | 无 | stdio服务器MCP命令 |
|
||||||
| args | 否 | [] | stdio服务器MCP命令参数 |
|
| arg | 否 | [] | stdio服务器MCP命令参数 |
|
||||||
| env | 否 | {} | stdio服务器环境变量 |
|
| env | 否 | {} | stdio服务器环境变量 |
|
||||||
| url | 远程服务器必填 | 无 | 远程MCP服务器地址 |
|
| url | sse服务器必填 | 无 | sse服务器地址 |
|
||||||
| headers | 否 | {} | 远程服务器http请求头,用于认证或其他设置 |
|
| headers | 否 | {} | sse模式下http请求头,用于认证或其他设置 |
|
||||||
| transport | 否 | 自动 | 远程MCP传输协议类型,可选 `sse` 或 `streamable_http` ,不填则自动探测 |
|
|
||||||
|
|
||||||
以下为在 Claude.app 的MCP服务器配置基础上增加的字段
|
以下为在 Claude.app 的MCP服务器配置基础上增加的字段
|
||||||
| 配置项 | 必填 | 默认值 | 说明 |
|
| 配置项 | 必填 | 默认值 | 说明 |
|
||||||
|
|
@ -256,12 +254,6 @@ LLMCHAT__MCP_SERVERS同样为一个dict,key为服务器名称,value配置的
|
||||||
"formulahendry/mcp-server-code-runner"
|
"formulahendry/mcp-server-code-runner"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"tavily": {
|
|
||||||
"friendly_name": "Tavily搜索",
|
|
||||||
"additional_prompt": "当你需要搜索最新的互联网信息时,请使用 tavily 工具。",
|
|
||||||
"url": "https://mcp.tavily.com/mcp/?tavilyApiKey=<your-api-key>",
|
|
||||||
"transport": "streamable_http"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
'
|
'
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -349,7 +349,6 @@ async def process_messages(context_id: int, is_group: bool = True):
|
||||||
logger.info(
|
logger.info(
|
||||||
f"开始处理{chat_type}消息 {context_type}:{context_id} 当前队列长度:{state.queue.qsize()}"
|
f"开始处理{chat_type}消息 {context_type}:{context_id} 当前队列长度:{state.queue.qsize()}"
|
||||||
)
|
)
|
||||||
try:
|
|
||||||
while not state.queue.empty():
|
while not state.queue.empty():
|
||||||
event = await state.queue.get()
|
event = await state.queue.get()
|
||||||
if is_group:
|
if is_group:
|
||||||
|
|
@ -359,10 +358,7 @@ async def process_messages(context_id: int, is_group: bool = True):
|
||||||
logger.debug(f"从队列获取消息 用户:{context_id} 消息ID:{event.message_id}")
|
logger.debug(f"从队列获取消息 用户:{context_id} 消息ID:{event.message_id}")
|
||||||
group_id = None
|
group_id = None
|
||||||
past_events_snapshot = []
|
past_events_snapshot = []
|
||||||
mcp_client = MCPClient.get_instance(
|
mcp_client = MCPClient.get_instance(plugin_config.mcp_servers)
|
||||||
plugin_config.mcp_servers,
|
|
||||||
plugin_config.mcp_server_cwd,
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
# 构建系统提示,分成多行以满足行长限制
|
# 构建系统提示,分成多行以满足行长限制
|
||||||
chat_type = "群聊" if is_group else "私聊"
|
chat_type = "群聊" if is_group else "私聊"
|
||||||
|
|
@ -604,11 +600,10 @@ async def process_messages(context_id: int, is_group: bool = True):
|
||||||
state.past_events.extendleft(reversed(past_events_snapshot))
|
state.past_events.extendleft(reversed(past_events_snapshot))
|
||||||
await handler.send(Message(f"服务暂时不可用,请稍后再试\n{e!s}"))
|
await handler.send(Message(f"服务暂时不可用,请稍后再试\n{e!s}"))
|
||||||
finally:
|
finally:
|
||||||
|
state.processing = False
|
||||||
state.queue.task_done()
|
state.queue.task_done()
|
||||||
# 不再需要每次都清理MCPClient,因为它现在是单例
|
# 不再需要每次都清理MCPClient,因为它现在是单例
|
||||||
# await mcp_client.cleanup()
|
# await mcp_client.cleanup()
|
||||||
finally:
|
|
||||||
state.processing = False
|
|
||||||
|
|
||||||
|
|
||||||
# 预设切换命令
|
# 预设切换命令
|
||||||
|
|
|
||||||
|
|
@ -24,9 +24,8 @@ class MCPServerConfig(BaseModel):
|
||||||
command: str | None = Field(None, description="stdio模式下MCP命令")
|
command: str | None = Field(None, description="stdio模式下MCP命令")
|
||||||
args: list[str] | None = Field([], description="stdio模式下MCP命令参数")
|
args: list[str] | None = Field([], description="stdio模式下MCP命令参数")
|
||||||
env: dict[str, str] | None = Field({}, description="stdio模式下MCP命令环境变量")
|
env: dict[str, str] | None = Field({}, description="stdio模式下MCP命令环境变量")
|
||||||
url: str | None = Field(None, description="远程MCP服务器地址")
|
url: str | None = Field(None, description="sse模式下MCP服务器地址")
|
||||||
headers: dict[str, str] | None = Field({}, description="远程MCP服务器http请求头,用于认证或其他设置")
|
headers: dict[str, str] | None = Field({}, description="sse模式下http请求头,用于认证或其他设置")
|
||||||
transport: str | None = Field(None, description="远程MCP传输协议类型,可选 'sse' 或 'streamable_http',默认自动检测")
|
|
||||||
|
|
||||||
# 额外字段
|
# 额外字段
|
||||||
friendly_name: str | None = Field(None, description="MCP服务器友好名称")
|
friendly_name: str | None = Field(None, description="MCP服务器友好名称")
|
||||||
|
|
@ -49,10 +48,6 @@ class ScopedConfig(BaseModel):
|
||||||
"你的回答应该尽量简洁、幽默、可以使用一些语气词、颜文字。你应该拒绝回答任何政治相关的问题。",
|
"你的回答应该尽量简洁、幽默、可以使用一些语气词、颜文字。你应该拒绝回答任何政治相关的问题。",
|
||||||
description="默认提示词",
|
description="默认提示词",
|
||||||
)
|
)
|
||||||
mcp_server_cwd: str | None = Field(
|
|
||||||
None,
|
|
||||||
description="command类型MCP服务器的全局工作目录(cwd)"
|
|
||||||
)
|
|
||||||
mcp_servers: dict[str, MCPServerConfig] = Field({}, description="MCP服务器配置")
|
mcp_servers: dict[str, MCPServerConfig] = Field({}, description="MCP服务器配置")
|
||||||
blacklist_user_ids: set[int] = Field(set(), description="黑名单用户ID列表")
|
blacklist_user_ids: set[int] = Field(set(), description="黑名单用户ID列表")
|
||||||
ignore_prefixes: list[str] = Field(
|
ignore_prefixes: list[str] = Field(
|
||||||
|
|
|
||||||
|
|
@ -3,11 +3,9 @@ from contextlib import AsyncExitStack
|
||||||
from time import monotonic
|
from time import monotonic
|
||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
|
|
||||||
import httpx
|
|
||||||
from mcp import ClientSession, StdioServerParameters
|
from mcp import ClientSession, StdioServerParameters
|
||||||
from mcp.client.sse import sse_client
|
from mcp.client.sse import sse_client
|
||||||
from mcp.client.stdio import stdio_client
|
from mcp.client.stdio import stdio_client
|
||||||
from mcp.client.streamable_http import streamable_http_client
|
|
||||||
from nonebot import logger
|
from nonebot import logger
|
||||||
|
|
||||||
from .config import MCPServerConfig
|
from .config import MCPServerConfig
|
||||||
|
|
@ -20,20 +18,12 @@ class MCPClient:
|
||||||
_SESSION_TTL_SECONDS = 600
|
_SESSION_TTL_SECONDS = 600
|
||||||
_SESSION_CLEANUP_INTERVAL_SECONDS = 60
|
_SESSION_CLEANUP_INTERVAL_SECONDS = 60
|
||||||
|
|
||||||
def __new__(
|
def __new__(cls, server_config: dict[str, MCPServerConfig] | None = None):
|
||||||
cls,
|
|
||||||
server_config: dict[str, MCPServerConfig] | None = None,
|
|
||||||
default_command_cwd: str | None = None,
|
|
||||||
):
|
|
||||||
if cls._instance is None:
|
if cls._instance is None:
|
||||||
cls._instance = super().__new__(cls)
|
cls._instance = super().__new__(cls)
|
||||||
return cls._instance
|
return cls._instance
|
||||||
|
|
||||||
def __init__(
|
def __init__(self, server_config: dict[str, MCPServerConfig] | None = None):
|
||||||
self,
|
|
||||||
server_config: dict[str, MCPServerConfig] | None = None,
|
|
||||||
default_command_cwd: str | None = None,
|
|
||||||
):
|
|
||||||
if self._initialized:
|
if self._initialized:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -42,7 +32,6 @@ class MCPClient:
|
||||||
|
|
||||||
logger.info(f"正在初始化MCPClient单例,共有{len(server_config)}个服务器配置")
|
logger.info(f"正在初始化MCPClient单例,共有{len(server_config)}个服务器配置")
|
||||||
self.server_config = server_config
|
self.server_config = server_config
|
||||||
self.default_command_cwd = default_command_cwd
|
|
||||||
self.sessions = {}
|
self.sessions = {}
|
||||||
self.exit_stack = AsyncExitStack()
|
self.exit_stack = AsyncExitStack()
|
||||||
self._session_exit_stacks: dict[str, AsyncExitStack] = {}
|
self._session_exit_stacks: dict[str, AsyncExitStack] = {}
|
||||||
|
|
@ -58,16 +47,12 @@ class MCPClient:
|
||||||
logger.debug("MCPClient单例初始化成功")
|
logger.debug("MCPClient单例初始化成功")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_instance(
|
def get_instance(cls, server_config: dict[str, MCPServerConfig] | None = None):
|
||||||
cls,
|
|
||||||
server_config: dict[str, MCPServerConfig] | None = None,
|
|
||||||
default_command_cwd: str | None = None,
|
|
||||||
):
|
|
||||||
"""获取MCPClient实例"""
|
"""获取MCPClient实例"""
|
||||||
if cls._instance is None:
|
if cls._instance is None:
|
||||||
if server_config is None:
|
if server_config is None:
|
||||||
raise ValueError("server_config must be provided for first initialization")
|
raise ValueError("server_config must be provided for first initialization")
|
||||||
cls._instance = cls(server_config, default_command_cwd)
|
cls._instance = cls(server_config)
|
||||||
return cls._instance
|
return cls._instance
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|
@ -90,45 +75,13 @@ class MCPClient:
|
||||||
config = self.server_config[server_name]
|
config = self.server_config[server_name]
|
||||||
session_stack = AsyncExitStack()
|
session_stack = AsyncExitStack()
|
||||||
if config.url:
|
if config.url:
|
||||||
transport_type = config.transport
|
transport = await session_stack.enter_async_context(
|
||||||
if transport_type == "streamable_http":
|
sse_client(url=config.url, headers=config.headers)
|
||||||
logger.debug(f"服务器[{server_name}]使用 streamable_http 传输协议")
|
|
||||||
http_client = await session_stack.enter_async_context(httpx.AsyncClient(headers=config.headers or {}))
|
|
||||||
read, write, _ = await session_stack.enter_async_context(
|
|
||||||
streamable_http_client(url=config.url, http_client=http_client)
|
|
||||||
)
|
)
|
||||||
transport = (read, write)
|
|
||||||
elif transport_type == "sse":
|
|
||||||
logger.debug(f"服务器[{server_name}]使用 sse 传输协议")
|
|
||||||
transport = await session_stack.enter_async_context(sse_client(url=config.url, headers=config.headers))
|
|
||||||
else:
|
|
||||||
# 未指定协议,自动探测:先尝试 sse,失败则回退到 streamable_http
|
|
||||||
# (sse 服务器对 streamable_http 的 POST 请求会卡住,反之 sse 连 streamable_http 服务器会快速返回 405)
|
|
||||||
logger.debug(f"服务器[{server_name}]未指定传输协议,开始自动探测")
|
|
||||||
probe_stack = AsyncExitStack()
|
|
||||||
try:
|
|
||||||
read, write = await probe_stack.enter_async_context(sse_client(url=config.url, headers=config.headers))
|
|
||||||
await session_stack.enter_async_context(probe_stack)
|
|
||||||
transport = (read, write)
|
|
||||||
logger.debug(f"服务器[{server_name}]自动探测成功: 使用 sse 传输协议")
|
|
||||||
except Exception as e:
|
|
||||||
await probe_stack.aclose()
|
|
||||||
logger.debug(f"服务器[{server_name}]sse 探测失败({e}),回退到 streamable_http")
|
|
||||||
http_client = await session_stack.enter_async_context(httpx.AsyncClient(headers=config.headers or {}))
|
|
||||||
read, write, _ = await session_stack.enter_async_context(
|
|
||||||
streamable_http_client(url=config.url, http_client=http_client)
|
|
||||||
)
|
|
||||||
transport = (read, write)
|
|
||||||
logger.debug(f"服务器[{server_name}]自动探测成功: 使用 streamable_http 传输协议")
|
|
||||||
elif config.command:
|
elif config.command:
|
||||||
stdio_params: dict[str, Any] = {
|
transport = await session_stack.enter_async_context(
|
||||||
"command": config.command,
|
cast(Any, stdio_client(StdioServerParameters(**config.model_dump())))
|
||||||
"args": config.args or [],
|
)
|
||||||
"env": config.env or {},
|
|
||||||
}
|
|
||||||
if self.default_command_cwd:
|
|
||||||
stdio_params["cwd"] = self.default_command_cwd
|
|
||||||
transport = await session_stack.enter_async_context(cast(Any, stdio_client(StdioServerParameters(**stdio_params))))
|
|
||||||
else:
|
else:
|
||||||
raise ValueError("Server config must have either url or command")
|
raise ValueError("Server config must have either url or command")
|
||||||
|
|
||||||
|
|
@ -226,6 +179,8 @@ class MCPClient:
|
||||||
|
|
||||||
logger.info(f"工具列表缓存完成,共缓存{len(available_tools)}个工具")
|
logger.info(f"工具列表缓存完成,共缓存{len(available_tools)}个工具")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def get_available_tools(self, is_group: bool):
|
async def get_available_tools(self, is_group: bool):
|
||||||
"""获取可用工具列表,使用缓存机制"""
|
"""获取可用工具列表,使用缓存机制"""
|
||||||
await self.init_tools_cache()
|
await self.init_tools_cache()
|
||||||
|
|
|
||||||
912
poetry.lock
generated
912
poetry.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,6 @@
|
||||||
[tool.poetry]
|
[tool.poetry]
|
||||||
name = "nonebot-plugin-llmchat"
|
name = "nonebot-plugin-llmchat"
|
||||||
version = "0.5.4"
|
version = "0.5.2"
|
||||||
description = "Nonebot AI group chat plugin supporting multiple API preset configurations"
|
description = "Nonebot AI group chat plugin supporting multiple API preset configurations"
|
||||||
license = "GPL"
|
license = "GPL"
|
||||||
authors = ["FuQuan i@fuquan.moe"]
|
authors = ["FuQuan i@fuquan.moe"]
|
||||||
|
|
@ -18,7 +18,7 @@ aiofiles = ">=24.0.0"
|
||||||
nonebot-plugin-apscheduler = "^0.5.0"
|
nonebot-plugin-apscheduler = "^0.5.0"
|
||||||
nonebot-adapter-onebot = "^2.0.0"
|
nonebot-adapter-onebot = "^2.0.0"
|
||||||
nonebot-plugin-localstore = "^0.7.3"
|
nonebot-plugin-localstore = "^0.7.3"
|
||||||
mcp = ">=1.24.0"
|
mcp = "^1.6.0"
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.poetry.group.dev.dependencies]
|
||||||
ruff = "^0.8.0"
|
ruff = "^0.8.0"
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue