feat: add MCP tool integration via MCPO (#11)
This commit is contained in:
+31
-8
@@ -72,7 +72,10 @@ def _is_allowed(user_id: int, settings: Settings) -> bool:
|
||||
"""Return True if the user is in the allow-list (or no list is configured)."""
|
||||
if not settings.telegram_allowed_user_ids:
|
||||
return True
|
||||
return user_id in settings.telegram_allowed_user_ids
|
||||
allowed = user_id in settings.telegram_allowed_user_ids
|
||||
if not allowed:
|
||||
logger.info("Ignoring update from unauthorized user %s", user_id)
|
||||
return allowed
|
||||
|
||||
|
||||
def _is_group_enabled(chat_id: int, settings: Settings) -> bool:
|
||||
@@ -82,6 +85,26 @@ def _is_group_enabled(chat_id: int, settings: Settings) -> bool:
|
||||
return chat_id in settings.telegram_group_ids
|
||||
|
||||
|
||||
def _is_chat_enabled(chat: Any, settings: Settings) -> bool:
|
||||
"""Return True if the chat is allowed.
|
||||
|
||||
Private chats are governed only by the user allow-list. Group/channel allow-listing
|
||||
applies only to non-private chats.
|
||||
"""
|
||||
if getattr(chat, "type", None) == "private":
|
||||
return True
|
||||
|
||||
allowed = _is_group_enabled(chat.id, settings)
|
||||
if not allowed:
|
||||
logger.info(
|
||||
"Ignoring update in unauthorized chat %s (type=%s); configured group IDs: %s",
|
||||
chat.id,
|
||||
getattr(chat, "type", None),
|
||||
settings.telegram_group_ids,
|
||||
)
|
||||
return allowed
|
||||
|
||||
|
||||
async def _send_long(update: Update, text: str) -> None:
|
||||
"""Send text, splitting across messages if it exceeds Telegram's 4096-char limit."""
|
||||
limit = 4096
|
||||
@@ -100,7 +123,7 @@ async def start_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> N
|
||||
return
|
||||
|
||||
chat = update.effective_chat
|
||||
if chat is None or not _is_group_enabled(chat.id, settings):
|
||||
if chat is None or not _is_chat_enabled(chat, settings):
|
||||
return
|
||||
|
||||
await update.message.reply_text( # type: ignore[union-attr]
|
||||
@@ -124,7 +147,7 @@ async def help_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
return
|
||||
|
||||
chat = update.effective_chat
|
||||
if chat is None or not _is_group_enabled(chat.id, settings):
|
||||
if chat is None or not _is_chat_enabled(chat, settings):
|
||||
return
|
||||
|
||||
await update.message.reply_text( # type: ignore[union-attr]
|
||||
@@ -152,7 +175,7 @@ async def clear_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> N
|
||||
return
|
||||
|
||||
chat = update.effective_chat
|
||||
if chat is None or not _is_group_enabled(chat.id, settings):
|
||||
if chat is None or not _is_chat_enabled(chat, settings):
|
||||
return
|
||||
|
||||
key = _thread_key(update)
|
||||
@@ -187,7 +210,7 @@ async def flush_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> N
|
||||
return
|
||||
|
||||
chat = update.effective_chat
|
||||
if chat is None or not _is_group_enabled(chat.id, settings):
|
||||
if chat is None or not _is_chat_enabled(chat, settings):
|
||||
return
|
||||
|
||||
key = _thread_key(update)
|
||||
@@ -270,7 +293,7 @@ async def recall_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
|
||||
return
|
||||
|
||||
chat = update.effective_chat
|
||||
if chat is None or not _is_group_enabled(chat.id, settings):
|
||||
if chat is None or not _is_chat_enabled(chat, settings):
|
||||
return
|
||||
|
||||
# If the user supplied a keyword query, search the knowledge base
|
||||
@@ -334,7 +357,7 @@ async def analyse_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
|
||||
return
|
||||
|
||||
chat = update.effective_chat
|
||||
if chat is None or not _is_group_enabled(chat.id, settings):
|
||||
if chat is None or not _is_chat_enabled(chat, settings):
|
||||
return
|
||||
|
||||
await update.message.reply_text("Running analysis, please wait...") # type: ignore[union-attr]
|
||||
@@ -389,7 +412,7 @@ async def message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
|
||||
chat = update.effective_chat
|
||||
if user is None or not _is_allowed(user.id, settings):
|
||||
return
|
||||
if chat is None or not _is_group_enabled(chat.id, settings):
|
||||
if chat is None or not _is_chat_enabled(chat, settings):
|
||||
return
|
||||
|
||||
text = update.message.text # type: ignore[union-attr]
|
||||
|
||||
@@ -17,6 +17,8 @@ logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
+91
-17
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -31,6 +32,8 @@ class ToolClient:
|
||||
self._api_key = api_key
|
||||
self._timeout = timeout
|
||||
self._spec: dict[str, Any] | None = None
|
||||
self._server_specs: dict[str, dict[str, Any]] | None = None
|
||||
self._tool_routes: dict[str, tuple[str, str]] = {}
|
||||
self._tools: list[dict[str, Any]] | None = None
|
||||
|
||||
@property
|
||||
@@ -59,11 +62,36 @@ class ToolClient:
|
||||
return self._spec
|
||||
|
||||
async def get_tools(self) -> list[dict[str, Any]]:
|
||||
"""Return OpenAI function-calling tool definitions from the OpenAPI spec."""
|
||||
"""Return OpenAI function-calling tool definitions from the OpenAPI spec.
|
||||
|
||||
MCPO config-file mode exposes each configured MCP server under its own subpath
|
||||
(for example ``/github/openapi.json``), while the root schema has no paths and
|
||||
only links to the per-server docs. In that mode, tool names are namespaced as
|
||||
``server__operation`` so similarly named tools from different MCP servers do not
|
||||
collide.
|
||||
"""
|
||||
if self._tools is not None:
|
||||
return self._tools
|
||||
spec = await self.get_spec()
|
||||
self._tools = _spec_to_openai_tools(spec)
|
||||
|
||||
specs = await self._get_server_specs()
|
||||
tools: list[dict[str, Any]] = []
|
||||
self._tool_routes = {}
|
||||
|
||||
for server_name, spec in specs.items():
|
||||
server_tools = _spec_to_openai_tools(spec)
|
||||
for tool in server_tools:
|
||||
function = tool["function"]
|
||||
operation_name = function["name"]
|
||||
if server_name:
|
||||
namespaced_name = f"{server_name}__{operation_name}"
|
||||
function["name"] = namespaced_name
|
||||
function["description"] = f"[{server_name}] {function.get('description', '')}"
|
||||
else:
|
||||
namespaced_name = operation_name
|
||||
self._tool_routes[namespaced_name] = (server_name, operation_name)
|
||||
tools.append(tool)
|
||||
|
||||
self._tools = tools
|
||||
logger.info("Registered %d tools from %s", len(self._tools), self._base_url)
|
||||
return self._tools
|
||||
|
||||
@@ -74,12 +102,19 @@ class ToolClient:
|
||||
partitions *arguments* into path params, query params, and request
|
||||
body, then makes the HTTP request.
|
||||
"""
|
||||
spec = await self.get_spec()
|
||||
await self.get_tools()
|
||||
if tool_name not in self._tool_routes:
|
||||
raise ValueError(f"Operation '{tool_name}' not found in spec")
|
||||
|
||||
server_name, operation_name = self._tool_routes[tool_name]
|
||||
specs = await self._get_server_specs()
|
||||
spec = specs[server_name]
|
||||
path, method, path_params, query_params, body = _resolve_operation(
|
||||
spec, tool_name, arguments
|
||||
spec, operation_name, arguments
|
||||
)
|
||||
|
||||
url = self._base_url + path
|
||||
base_path = f"/{server_name}" if server_name else ""
|
||||
url = self._base_url + base_path + path
|
||||
for key, value in path_params.items():
|
||||
url = url.replace(f"{{{key}}}", str(value))
|
||||
|
||||
@@ -100,15 +135,59 @@ class ToolClient:
|
||||
pass
|
||||
return resp.text
|
||||
|
||||
async def _get_server_specs(self) -> dict[str, dict[str, Any]]:
|
||||
"""Return OpenAPI specs keyed by MCPO server name.
|
||||
|
||||
``""`` denotes the root OpenAPI server. Non-empty keys denote MCPO
|
||||
config-file subservers such as ``github`` or ``memory``.
|
||||
"""
|
||||
if self._server_specs is not None:
|
||||
return self._server_specs
|
||||
|
||||
root_spec = await self.get_spec()
|
||||
if root_spec.get("paths"):
|
||||
self._server_specs = {"": root_spec}
|
||||
return self._server_specs
|
||||
|
||||
server_names = _discover_mcpo_server_names(root_spec)
|
||||
if not server_names:
|
||||
self._server_specs = {"": root_spec}
|
||||
return self._server_specs
|
||||
|
||||
specs: dict[str, dict[str, Any]] = {}
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as http:
|
||||
for server_name in server_names:
|
||||
resp = await http.get(
|
||||
f"{self._base_url}/{server_name}/openapi.json",
|
||||
headers=self._headers(),
|
||||
)
|
||||
resp.raise_for_status()
|
||||
spec = resp.json()
|
||||
specs[server_name] = spec
|
||||
logger.info(
|
||||
"Loaded OpenAPI spec from %s/%s (%d paths)",
|
||||
self._base_url,
|
||||
server_name,
|
||||
len(spec.get("paths", {})),
|
||||
)
|
||||
|
||||
self._server_specs = specs
|
||||
return self._server_specs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenAPI → OpenAI tool-definition helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _resolve_ref(
|
||||
schema: dict[str, Any], components: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
def _discover_mcpo_server_names(spec: dict[str, Any]) -> list[str]:
|
||||
"""Extract MCPO config-file server names from the root OpenAPI description."""
|
||||
description = str(spec.get("info", {}).get("description", ""))
|
||||
names = re.findall(r"\[([^\]]+)]\(/([^/]+)/docs\)", description)
|
||||
return [name for name, path_name in names if name == path_name]
|
||||
|
||||
|
||||
def _resolve_ref(schema: dict[str, Any], components: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Recursively resolve a ``$ref`` inside an OpenAPI schema."""
|
||||
if "$ref" not in schema:
|
||||
return schema
|
||||
@@ -138,8 +217,7 @@ def _schema_to_json_schema(
|
||||
result["items"] = _schema_to_json_schema(resolved["items"], components)
|
||||
if "properties" in resolved:
|
||||
result["properties"] = {
|
||||
k: _schema_to_json_schema(v, components)
|
||||
for k, v in resolved["properties"].items()
|
||||
k: _schema_to_json_schema(v, components) for k, v in resolved["properties"].items()
|
||||
}
|
||||
if "required" in resolved:
|
||||
result["required"] = resolved["required"]
|
||||
@@ -175,9 +253,7 @@ def _spec_to_openai_tools(spec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
# URL / query parameters
|
||||
for param in op.get("parameters", []):
|
||||
name: str = param["name"]
|
||||
schema = _schema_to_json_schema(
|
||||
param.get("schema", {"type": "string"}), components
|
||||
)
|
||||
schema = _schema_to_json_schema(param.get("schema", {"type": "string"}), components)
|
||||
if param.get("description"):
|
||||
schema["description"] = param["description"]
|
||||
properties[name] = schema
|
||||
@@ -188,9 +264,7 @@ def _spec_to_openai_tools(spec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
rb: dict[str, Any] = op.get("requestBody", {})
|
||||
if rb:
|
||||
json_content = rb.get("content", {}).get("application/json", {})
|
||||
body_schema = _schema_to_json_schema(
|
||||
json_content.get("schema", {}), components
|
||||
)
|
||||
body_schema = _schema_to_json_schema(json_content.get("schema", {}), components)
|
||||
if body_schema.get("type") == "object":
|
||||
for prop_name, prop_schema in body_schema.get("properties", {}).items():
|
||||
properties[prop_name] = prop_schema
|
||||
|
||||
Reference in New Issue
Block a user