make mcp connector more simple
This commit is contained in:
7 files changed
+1644
-191
No files matched your search
@@ -9,6 +9,15 @@ from homeagent.mcp.auth import (
|
||||
PendingOAuthDevice,
|
||||
PendingOAuthPKCE,
|
||||
)
|
||||
from homeagent.mcp.autodiscover import (
|
||||
SmartProbeResult,
|
||||
derive_connector_name_from_command,
|
||||
derive_connector_name_from_url,
|
||||
looks_like_smart_mcp_input,
|
||||
parse_smart_input,
|
||||
smart_apply_credentials_and_probe,
|
||||
smart_connect_connector,
|
||||
)
|
||||
from homeagent.mcp.client import MCPClient, MCPProtocolError
|
||||
from homeagent.mcp.manager import MCPConnectorManager
|
||||
from homeagent.mcp.models import (
|
||||
|
||||
@@ -0,0 +1,848 @@
|
||||
"""Zero-config smart auto-discovery and credential probing for MCP connectors."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, Optional
|
||||
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
|
||||
|
||||
import yaml
|
||||
|
||||
from homeagent.mcp.auth import MCPAuthError, MCPAuthRequiredError
|
||||
from homeagent.mcp.client import MCPClient, MCPProtocolError
|
||||
from homeagent.mcp.manager import MCPConnectorManager
|
||||
from homeagent.mcp.models import (
|
||||
MCPAuthConfig,
|
||||
MCPConnectorConfig,
|
||||
MCPConnectorState,
|
||||
normalize_connector_name,
|
||||
parse_connectors_payload,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_QUERY_AUTH_KEYS = frozenset({"api_key", "apikey", "key", "token", "access_token", "auth", "secret"})
|
||||
_GENERIC_SUBDOMAINS = frozenset({"mcp", "api", "www", "app", "server", "remote", "beta", "staging", "dev", "v1", "v2"})
|
||||
_GENERIC_PATH_PARTS = frozenset({"mcp", "sse", "api", "v1", "v2", "v3", "rpc", "jsonrpc", "stream", "messages"})
|
||||
_ENV_ASSIGN_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
|
||||
_STDIO_HINT_ENV_RE = re.compile(r"\b([A-Z][A-Z0-9_]{2,}_(?:TOKEN|KEY|API_KEY|SECRET|PASSWORD|PAT))\b")
|
||||
_COMMON_STDIO_COMMANDS = frozenset(
|
||||
{
|
||||
"npx",
|
||||
"pnpx",
|
||||
"bunx",
|
||||
"uvx",
|
||||
"uv",
|
||||
"pipx",
|
||||
"python",
|
||||
"python3",
|
||||
"node",
|
||||
"deno",
|
||||
"bun",
|
||||
"docker",
|
||||
"podman",
|
||||
"sh",
|
||||
"bash",
|
||||
"go",
|
||||
"cargo",
|
||||
"java",
|
||||
"ruby",
|
||||
"php",
|
||||
}
|
||||
)
|
||||
|
||||
SmartOutcome = Literal[
|
||||
"connected",
|
||||
"oauth_pkce_ready",
|
||||
"oauth_device_ready",
|
||||
"need_basic",
|
||||
"need_credentials",
|
||||
"stdio_error",
|
||||
"error",
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class SmartProbeResult:
|
||||
"""Result of smart auto-connect or credential probing."""
|
||||
|
||||
outcome: SmartOutcome
|
||||
state: MCPConnectorState
|
||||
oauth_info: Optional[dict[str, Any]] = None
|
||||
discovered_oauth: Optional[dict[str, Any]] = None
|
||||
detected_auth_label: Optional[str] = None
|
||||
hinted_env_vars: list[str] = field(default_factory=list)
|
||||
probe_attempts: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _dedupe_name(base: str, existing: set[str]) -> str:
|
||||
try:
|
||||
clean = normalize_connector_name(base)
|
||||
except ValueError:
|
||||
clean = "mcp_server"
|
||||
if clean not in existing:
|
||||
return clean
|
||||
idx = 2
|
||||
while f"{clean}_{idx}" in existing:
|
||||
idx += 1
|
||||
return f"{clean}_{idx}"
|
||||
|
||||
|
||||
def derive_connector_name_from_url(url: str, existing: Optional[set[str]] = None) -> str:
|
||||
"""Derive a clean, friendly connector slug from an MCP server URL."""
|
||||
existing_set = existing or set()
|
||||
parsed = urlparse(url)
|
||||
host = (parsed.hostname or "").lower()
|
||||
path_parts = [p for p in parsed.path.split("/") if p and p.lower() not in _GENERIC_PATH_PARTS]
|
||||
|
||||
candidate = ""
|
||||
if host in ("localhost", "127.0.0.1", "::1") or re.match(r"^\d+\.\d+\.\d+\.\d+$", host):
|
||||
if path_parts:
|
||||
candidate = path_parts[0]
|
||||
elif parsed.port:
|
||||
candidate = f"local_{parsed.port}"
|
||||
else:
|
||||
candidate = "local_mcp"
|
||||
elif host:
|
||||
labels = [lbl for lbl in host.split(".") if lbl]
|
||||
# Strip TLD (and ccTLD like .co.uk)
|
||||
if len(labels) >= 2:
|
||||
labels = labels[:-1]
|
||||
if len(labels) >= 2 and labels[-1] in ("co", "com", "org", "net", "gov"):
|
||||
labels = labels[:-1]
|
||||
meaningful = [lbl for lbl in labels if lbl not in _GENERIC_SUBDOMAINS]
|
||||
if meaningful:
|
||||
candidate = meaningful[-1]
|
||||
elif labels:
|
||||
candidate = labels[-1]
|
||||
elif path_parts:
|
||||
candidate = path_parts[0]
|
||||
|
||||
if not candidate:
|
||||
candidate = path_parts[0] if path_parts else "mcp_server"
|
||||
|
||||
return _dedupe_name(candidate, existing_set)
|
||||
|
||||
|
||||
def derive_connector_name_from_command(
|
||||
command: str,
|
||||
args: list[str],
|
||||
existing: Optional[set[str]] = None,
|
||||
) -> str:
|
||||
"""Derive a friendly connector slug from a stdio command + args."""
|
||||
existing_set = existing or set()
|
||||
cmd_base = Path(command).stem.lower()
|
||||
candidate = ""
|
||||
|
||||
if cmd_base in ("npx", "pnpx", "bunx", "uvx", "pipx"):
|
||||
for arg in args:
|
||||
if arg.startswith("-"):
|
||||
continue
|
||||
pkg = arg.strip()
|
||||
# Drop npm version suffix like @1.2.3
|
||||
if "@" in pkg[1:]:
|
||||
pkg = pkg[: pkg.rfind("@")]
|
||||
# Split scope/package
|
||||
if "/" in pkg:
|
||||
scope, name = pkg.split("/", 1)
|
||||
scope = scope.lstrip("@")
|
||||
cleaned_name = re.sub(r"^(?:mcp[-_]?server[-_]?|server[-_]?|mcp[-_]?)", "", name, flags=re.IGNORECASE)
|
||||
cleaned_name = re.sub(r"[-_]?mcp(?:[-_]?server)?$", "", cleaned_name, flags=re.IGNORECASE)
|
||||
if cleaned_name and cleaned_name.lower() not in ("server", "mcp"):
|
||||
candidate = cleaned_name
|
||||
else:
|
||||
candidate = scope
|
||||
else:
|
||||
cleaned_name = re.sub(r"^(?:mcp[-_]?server[-_]?|server[-_]?|mcp[-_]?)", "", pkg, flags=re.IGNORECASE)
|
||||
cleaned_name = re.sub(r"[-_]?mcp(?:[-_]?server)?$", "", cleaned_name, flags=re.IGNORECASE)
|
||||
candidate = cleaned_name or pkg
|
||||
break
|
||||
elif cmd_base in ("python", "python3", "node", "deno", "bun", "uv"):
|
||||
for arg in args:
|
||||
if arg.startswith("-") or arg in ("run", "exec", "-m"):
|
||||
continue
|
||||
candidate = Path(arg).stem
|
||||
break
|
||||
|
||||
if not candidate:
|
||||
candidate = cmd_base or "stdio_mcp"
|
||||
|
||||
return _dedupe_name(candidate, existing_set)
|
||||
|
||||
|
||||
def _strip_code_fences(text: str) -> str:
|
||||
s = text.strip()
|
||||
if s.startswith("```"):
|
||||
lines = s.splitlines()
|
||||
if lines and lines[0].startswith("```"):
|
||||
lines = lines[1:]
|
||||
if lines and lines[-1].strip() == "```":
|
||||
lines = lines[:-1]
|
||||
return "\n".join(lines).strip()
|
||||
return s
|
||||
|
||||
|
||||
def _extract_url_credentials(url: str) -> tuple[str, MCPAuthConfig]:
|
||||
"""Extract embedded Basic auth (`user:pass@host`) or API-key query params from a URL."""
|
||||
parsed = urlparse(url)
|
||||
auth = MCPAuthConfig(type="none")
|
||||
|
||||
netloc = parsed.netloc
|
||||
if parsed.username is not None:
|
||||
auth = MCPAuthConfig(
|
||||
type="basic",
|
||||
username=parsed.username,
|
||||
password=parsed.password or "",
|
||||
)
|
||||
host_part = parsed.hostname or ""
|
||||
if ":" in host_part and not host_part.startswith("["):
|
||||
host_part = f"[{host_part}]"
|
||||
netloc = f"{host_part}:{parsed.port}" if parsed.port else host_part
|
||||
|
||||
query_pairs = parse_qsl(parsed.query, keep_blank_values=True)
|
||||
remaining_pairs: list[tuple[str, str]] = []
|
||||
if auth.type == "none":
|
||||
for k, v in query_pairs:
|
||||
if k.lower() in _QUERY_AUTH_KEYS and v and auth.type == "none":
|
||||
auth = MCPAuthConfig(
|
||||
type="api_key",
|
||||
api_key=v,
|
||||
api_key_in="query",
|
||||
query_param=k,
|
||||
)
|
||||
else:
|
||||
remaining_pairs.append((k, v))
|
||||
else:
|
||||
remaining_pairs = query_pairs
|
||||
|
||||
clean_url = urlunparse(
|
||||
parsed._replace(
|
||||
netloc=netloc,
|
||||
query=urlencode(remaining_pairs, doseq=True),
|
||||
)
|
||||
)
|
||||
return clean_url, auth
|
||||
|
||||
|
||||
def _parse_curl_input(
|
||||
raw_text: str,
|
||||
*,
|
||||
existing_names: set[str],
|
||||
default_timeout: int,
|
||||
) -> MCPConnectorConfig:
|
||||
"""Parse a pasted `curl ...` snippet into an `MCPConnectorConfig`."""
|
||||
normalized = raw_text.replace("\\\n", " ").strip()
|
||||
tokens = shlex.split(normalized)
|
||||
url: Optional[str] = None
|
||||
headers: dict[str, str] = {}
|
||||
basic_user: Optional[str] = None
|
||||
basic_pass: Optional[str] = None
|
||||
|
||||
i = 1
|
||||
while i < len(tokens):
|
||||
tok = tokens[i]
|
||||
if tok in ("-H", "--header") and i + 1 < len(tokens):
|
||||
hdr = tokens[i + 1]
|
||||
if ":" in hdr:
|
||||
k, v = hdr.split(":", 1)
|
||||
headers[k.strip()] = v.strip()
|
||||
i += 2
|
||||
continue
|
||||
if tok in ("-u", "--user") and i + 1 < len(tokens):
|
||||
cred = tokens[i + 1]
|
||||
if ":" in cred:
|
||||
basic_user, basic_pass = cred.split(":", 1)
|
||||
else:
|
||||
basic_user, basic_pass = cred, ""
|
||||
i += 2
|
||||
continue
|
||||
if tok in ("-X", "--request", "-d", "--data", "--data-raw", "--data-binary"):
|
||||
i += 2
|
||||
continue
|
||||
if tok.startswith("http://") or tok.startswith("https://"):
|
||||
url = tok
|
||||
i += 1
|
||||
|
||||
if not url:
|
||||
raise ValueError("Не удалось найти URL в команде `curl`.")
|
||||
|
||||
clean_url, url_auth = _extract_url_credentials(url)
|
||||
auth = url_auth
|
||||
extra_headers: dict[str, str] = {}
|
||||
|
||||
if basic_user is not None:
|
||||
auth = MCPAuthConfig(type="basic", username=basic_user, password=basic_pass or "")
|
||||
|
||||
for k, v in headers.items():
|
||||
kl = k.lower()
|
||||
if kl in ("content-type", "accept"):
|
||||
continue
|
||||
if kl == "authorization" and auth.type == "none":
|
||||
parts = v.split(None, 1)
|
||||
if len(parts) == 2 and parts[0].lower() == "bearer":
|
||||
auth = MCPAuthConfig(type="bearer", token=parts[1].strip())
|
||||
continue
|
||||
if kl in ("x-api-key", "api-key") and auth.type == "none":
|
||||
auth = MCPAuthConfig(type="api_key", api_key=v, header_name=k, api_key_in="header")
|
||||
continue
|
||||
extra_headers[k] = v
|
||||
|
||||
if extra_headers and auth.type == "none":
|
||||
auth = MCPAuthConfig(type="headers", headers=extra_headers)
|
||||
extra_headers = {}
|
||||
|
||||
name = derive_connector_name_from_url(clean_url, existing_names)
|
||||
return MCPConnectorConfig(
|
||||
name=name,
|
||||
transport="auto",
|
||||
url=clean_url,
|
||||
headers=extra_headers,
|
||||
auth=auth,
|
||||
timeout_seconds=default_timeout,
|
||||
source="bot",
|
||||
)
|
||||
|
||||
|
||||
def _looks_like_structured_config(text: str) -> bool:
|
||||
stripped = _strip_code_fences(text)
|
||||
if not stripped:
|
||||
return False
|
||||
if stripped.startswith("{") or stripped.startswith("["):
|
||||
return True
|
||||
if "mcpServers:" in stripped or stripped.startswith("connectors:"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _looks_like_url(token: str) -> bool:
|
||||
return token.startswith("http://") or token.startswith("https://")
|
||||
|
||||
|
||||
def _looks_like_stdio_command(tokens: list[str]) -> bool:
|
||||
if not tokens:
|
||||
return False
|
||||
idx = 0
|
||||
while idx < len(tokens) and _ENV_ASSIGN_RE.match(tokens[idx]):
|
||||
idx += 1
|
||||
if idx >= len(tokens):
|
||||
return False
|
||||
cmd = tokens[idx]
|
||||
cmd_base = Path(cmd).name.lower()
|
||||
if cmd_base in _COMMON_STDIO_COMMANDS:
|
||||
return True
|
||||
if cmd.startswith("/") or cmd.startswith("./") or cmd.startswith("~/"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def looks_like_smart_mcp_input(raw_text: str) -> bool:
|
||||
"""Return True if raw_text looks like a URL, JSON/YAML config, curl command, or stdio command."""
|
||||
s = raw_text.strip()
|
||||
if not s:
|
||||
return False
|
||||
if _looks_like_structured_config(s):
|
||||
return True
|
||||
if s.lower().startswith("curl "):
|
||||
return True
|
||||
try:
|
||||
tokens = shlex.split(s)
|
||||
except ValueError:
|
||||
tokens = s.split()
|
||||
if not tokens:
|
||||
return False
|
||||
if _looks_like_url(tokens[0]):
|
||||
return True
|
||||
if len(tokens) >= 2 and _looks_like_url(tokens[1]):
|
||||
return True
|
||||
if _looks_like_stdio_command(tokens):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def parse_smart_input(
|
||||
raw_text: str,
|
||||
*,
|
||||
existing_names: Optional[set[str]] = None,
|
||||
default_timeout: int = 60,
|
||||
) -> tuple[list[MCPConnectorConfig], Optional[str]]:
|
||||
"""Parse any free-form user input (URL, command, JSON/YAML, curl) into connector config(s).
|
||||
|
||||
Returns `(configs, inline_credential)` where `inline_credential` is an optional trailing
|
||||
token/key supplied alongside a URL (e.g. `https://mcp.example.com/mcp ghp_xxx`) that should
|
||||
be probed automatically.
|
||||
"""
|
||||
existing = set(existing_names or set())
|
||||
text = raw_text.strip()
|
||||
if not text:
|
||||
raise ValueError("Пустой ввод. Отправьте URL, команду запуска или JSON-конфиг MCP-сервера.")
|
||||
|
||||
# 1. JSON or YAML snippet
|
||||
if _looks_like_structured_config(text):
|
||||
cleaned = _strip_code_fences(text)
|
||||
try:
|
||||
parsed = json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
parsed = yaml.safe_load(cleaned)
|
||||
|
||||
# Support bare single server object without "name": {"url": "...", ...} or {"command": "..."}
|
||||
if isinstance(parsed, dict) and "mcpServers" not in parsed and "connectors" not in parsed:
|
||||
has_direct_target = any(k in parsed for k in ("url", "serverUrl", "server_url", "command"))
|
||||
if has_direct_target and "name" not in parsed:
|
||||
parsed = dict(parsed)
|
||||
target_url = parsed.get("url") or parsed.get("serverUrl") or parsed.get("server_url")
|
||||
if target_url:
|
||||
parsed["name"] = derive_connector_name_from_url(str(target_url), existing)
|
||||
else:
|
||||
parsed["name"] = derive_connector_name_from_command(
|
||||
str(parsed.get("command") or "stdio"),
|
||||
list(parsed.get("args") or []),
|
||||
existing,
|
||||
)
|
||||
|
||||
configs = parse_connectors_payload(parsed, source="bot", default_timeout=default_timeout)
|
||||
if not configs:
|
||||
raise ValueError("В переданном JSON/YAML не найдено ни одного MCP-сервера.")
|
||||
return configs, None
|
||||
|
||||
# 2. curl command
|
||||
if text.lower().startswith("curl "):
|
||||
cfg = _parse_curl_input(text, existing_names=existing, default_timeout=default_timeout)
|
||||
return [cfg], None
|
||||
|
||||
# Tokenize shell-style
|
||||
try:
|
||||
tokens = shlex.split(text)
|
||||
except ValueError as e:
|
||||
raise ValueError(f"Не удалось разобрать ввод: {e}") from e
|
||||
|
||||
if not tokens:
|
||||
raise ValueError("Пустой ввод.")
|
||||
|
||||
# 3. URL directly: `<url>` or `<url> <token_or_key>`
|
||||
if _looks_like_url(tokens[0]):
|
||||
clean_url, url_auth = _extract_url_credentials(tokens[0])
|
||||
name = derive_connector_name_from_url(clean_url, existing)
|
||||
inline_cred = " ".join(tokens[1:]).strip() or None
|
||||
cfg = MCPConnectorConfig(
|
||||
name=name,
|
||||
transport="auto",
|
||||
url=clean_url,
|
||||
auth=url_auth,
|
||||
timeout_seconds=default_timeout,
|
||||
source="bot",
|
||||
)
|
||||
return [cfg], inline_cred
|
||||
|
||||
# 4. `<name> <url>` or `<name> <url> <token_or_key>`
|
||||
if len(tokens) >= 2 and _looks_like_url(tokens[1]):
|
||||
name = normalize_connector_name(tokens[0])
|
||||
clean_url, url_auth = _extract_url_credentials(tokens[1])
|
||||
inline_cred = " ".join(tokens[2:]).strip() or None
|
||||
cfg = MCPConnectorConfig(
|
||||
name=name,
|
||||
transport="auto",
|
||||
url=clean_url,
|
||||
auth=url_auth,
|
||||
timeout_seconds=default_timeout,
|
||||
source="bot",
|
||||
)
|
||||
return [cfg], inline_cred
|
||||
|
||||
# 5. `<name> stdio <command> [args...]`
|
||||
if len(tokens) >= 3 and tokens[1].lower() == "stdio":
|
||||
name = normalize_connector_name(tokens[0])
|
||||
env: dict[str, str] = {}
|
||||
idx = 2
|
||||
while idx < len(tokens):
|
||||
m = _ENV_ASSIGN_RE.match(tokens[idx])
|
||||
if not m:
|
||||
break
|
||||
env[m.group(1)] = m.group(2)
|
||||
idx += 1
|
||||
if idx >= len(tokens):
|
||||
raise ValueError("Укажите команду запуска после `stdio`.")
|
||||
cfg = MCPConnectorConfig(
|
||||
name=name,
|
||||
transport="stdio",
|
||||
command=tokens[idx],
|
||||
args=tokens[idx + 1 :],
|
||||
env=env,
|
||||
timeout_seconds=default_timeout,
|
||||
source="bot",
|
||||
)
|
||||
return [cfg], None
|
||||
|
||||
# 6. Direct stdio command: `[KEY=VAL ...] npx -y @modelcontextprotocol/server-filesystem /tmp`
|
||||
if _looks_like_stdio_command(tokens):
|
||||
env = {}
|
||||
idx = 0
|
||||
while idx < len(tokens):
|
||||
m = _ENV_ASSIGN_RE.match(tokens[idx])
|
||||
if not m:
|
||||
break
|
||||
env[m.group(1)] = m.group(2)
|
||||
idx += 1
|
||||
command = tokens[idx]
|
||||
args = tokens[idx + 1 :]
|
||||
name = derive_connector_name_from_command(command, args, existing)
|
||||
cfg = MCPConnectorConfig(
|
||||
name=name,
|
||||
transport="stdio",
|
||||
command=command,
|
||||
args=args,
|
||||
env=env,
|
||||
timeout_seconds=default_timeout,
|
||||
source="bot",
|
||||
)
|
||||
return [cfg], None
|
||||
|
||||
raise ValueError(
|
||||
"Не удалось распознать MCP-сервер. Отправьте:\n"
|
||||
"• **URL** (например: `https://mcp.linear.app/mcp`)\n"
|
||||
"• **Команду** (например: `npx -y @modelcontextprotocol/server-filesystem /tmp`)\n"
|
||||
"• **JSON-конфиг** (`{\"mcpServers\": {...}}`)\n"
|
||||
"• Или **`curl`** команду"
|
||||
)
|
||||
|
||||
|
||||
def _extract_hinted_env_vars(error_text: Optional[str]) -> list[str]:
|
||||
if not error_text:
|
||||
return []
|
||||
seen: list[str] = []
|
||||
for match in _STDIO_HINT_ENV_RE.finditer(error_text):
|
||||
var = match.group(1)
|
||||
if var not in seen:
|
||||
seen.append(var)
|
||||
return seen[:5]
|
||||
|
||||
|
||||
def _is_auth_failure(state: MCPConnectorState) -> bool:
|
||||
if state.status == "auth_required":
|
||||
return True
|
||||
if state.last_status_code in (401, 403):
|
||||
return True
|
||||
err = (state.last_error or "").lower()
|
||||
return any(hint in err for hint in ("401", "403", "unauthorized", "forbidden", "authentication required"))
|
||||
|
||||
|
||||
async def smart_connect_connector(
|
||||
manager: MCPConnectorManager,
|
||||
config: MCPConnectorConfig,
|
||||
*,
|
||||
inline_credential: Optional[str] = None,
|
||||
) -> SmartProbeResult:
|
||||
"""Save a connector, auto-probe transport & auth, and kick off OAuth automatically if advertised."""
|
||||
if inline_credential and config.transport != "stdio" and config.auth.type == "none":
|
||||
await manager.add_or_update_connector(config, connect_now=False, persist=True)
|
||||
return await smart_apply_credentials_and_probe(manager, config.name, inline_credential)
|
||||
|
||||
state = await manager.add_or_update_connector(config, connect_now=True, persist=True)
|
||||
if state.status == "connected":
|
||||
return SmartProbeResult(
|
||||
outcome="connected",
|
||||
state=state,
|
||||
detected_auth_label=config.auth.summary(),
|
||||
)
|
||||
|
||||
if config.transport == "stdio":
|
||||
return SmartProbeResult(
|
||||
outcome="stdio_error",
|
||||
state=state,
|
||||
hinted_env_vars=_extract_hinted_env_vars(state.last_error),
|
||||
)
|
||||
|
||||
if _is_auth_failure(state):
|
||||
challenge = state.oauth_challenge or {}
|
||||
www_auth = str(challenge.get("www_authenticate") or "")
|
||||
resource_meta_url = challenge.get("resource_metadata_url")
|
||||
|
||||
# 1. Try OAuth 2.1 auto-discovery (RFC 9728 + RFC 8414 + RFC 7591 DCR)
|
||||
discovered: dict[str, Any] = {}
|
||||
if config.url:
|
||||
try:
|
||||
discovered = await manager.auth_manager.discover_oauth_metadata(
|
||||
config.url,
|
||||
resource_metadata_url=resource_meta_url,
|
||||
verify_ssl=config.verify_ssl,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug("Smart OAuth discovery error for '%s': %s", config.name, e)
|
||||
|
||||
has_pkce = bool(discovered.get("authorization_endpoint") and discovered.get("token_endpoint"))
|
||||
can_auto_pkce = has_pkce and bool(config.auth.client_id or discovered.get("registration_endpoint"))
|
||||
|
||||
if can_auto_pkce:
|
||||
try:
|
||||
oauth_info = await manager.start_oauth(config.name)
|
||||
return SmartProbeResult(
|
||||
outcome="oauth_pkce_ready",
|
||||
state=manager.get_connector(config.name) or state,
|
||||
oauth_info=oauth_info,
|
||||
discovered_oauth=discovered,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info("Auto OAuth PKCE start skipped for '%s': %s", config.name, e)
|
||||
|
||||
# 2. Check Basic Auth challenge
|
||||
if www_auth.lower().startswith("basic"):
|
||||
return SmartProbeResult(
|
||||
outcome="need_basic",
|
||||
state=state,
|
||||
discovered_oauth=discovered or None,
|
||||
)
|
||||
|
||||
# 3. Ask user for a single credential paste (token / API key / user:pass / header)
|
||||
return SmartProbeResult(
|
||||
outcome="need_credentials",
|
||||
state=state,
|
||||
discovered_oauth=discovered or None,
|
||||
)
|
||||
|
||||
return SmartProbeResult(outcome="error", state=state)
|
||||
|
||||
|
||||
def _parse_kv_multiline(raw: str) -> dict[str, str]:
|
||||
result: dict[str, str] = {}
|
||||
for line in raw.splitlines():
|
||||
for part in line.split(";"):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
if "=" in part and (":" not in part or part.index("=") < part.index(":")):
|
||||
k, v = part.split("=", 1)
|
||||
elif ":" in part:
|
||||
k, v = part.split(":", 1)
|
||||
else:
|
||||
continue
|
||||
k, v = k.strip(), v.strip()
|
||||
if k:
|
||||
result[k] = v
|
||||
return result
|
||||
|
||||
|
||||
def _build_credential_candidates(
|
||||
raw_secret: str,
|
||||
discovered_oauth: Optional[dict[str, Any]] = None,
|
||||
) -> list[tuple[str, MCPAuthConfig]]:
|
||||
"""Build an ordered list of `(label, MCPAuthConfig)` candidates to probe automatically."""
|
||||
text = raw_secret.strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
disc = discovered_oauth or {}
|
||||
candidates: list[tuple[str, MCPAuthConfig]] = []
|
||||
|
||||
# 1. Explicit key=value OAuth parameters (multi-param)
|
||||
kv = _parse_kv_multiline(text)
|
||||
if "client_id" in kv and "client_secret" in kv and "authorization_url" not in kv:
|
||||
candidates.append(
|
||||
(
|
||||
"OAuth 2.0 Client Credentials",
|
||||
MCPAuthConfig(
|
||||
type="oauth2_client_credentials",
|
||||
client_id=kv["client_id"],
|
||||
client_secret=kv["client_secret"],
|
||||
token_url=kv.get("token_url") or disc.get("token_endpoint"),
|
||||
scope=kv.get("scope"),
|
||||
audience=kv.get("audience"),
|
||||
),
|
||||
)
|
||||
)
|
||||
return candidates
|
||||
|
||||
if "refresh_token" in kv:
|
||||
candidates.append(
|
||||
(
|
||||
"OAuth 2.0 Refresh Token",
|
||||
MCPAuthConfig(
|
||||
type="oauth2_refresh_token",
|
||||
refresh_token=kv["refresh_token"],
|
||||
token_url=kv.get("token_url") or disc.get("token_endpoint"),
|
||||
client_id=kv.get("client_id"),
|
||||
client_secret=kv.get("client_secret"),
|
||||
scope=kv.get("scope"),
|
||||
),
|
||||
)
|
||||
)
|
||||
return candidates
|
||||
|
||||
if "client_id" in kv and (
|
||||
"authorization_url" in kv or disc.get("authorization_endpoint")
|
||||
):
|
||||
candidates.append(
|
||||
(
|
||||
"OAuth 2.1 PKCE",
|
||||
MCPAuthConfig(
|
||||
type="oauth2_pkce",
|
||||
client_id=kv["client_id"],
|
||||
client_secret=kv.get("client_secret"),
|
||||
authorization_url=kv.get("authorization_url") or disc.get("authorization_endpoint"),
|
||||
token_url=kv.get("token_url") or disc.get("token_endpoint"),
|
||||
scope=kv.get("scope"),
|
||||
),
|
||||
)
|
||||
)
|
||||
return candidates
|
||||
|
||||
# 2. Explicit `Authorization: ...` or `Bearer <tok>` / `Token <tok>` / `ApiKey <tok>`
|
||||
lower = text.lower()
|
||||
if "\n" not in text and lower.startswith("bearer "):
|
||||
tok = text[7:].strip()
|
||||
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=tok)))
|
||||
return candidates
|
||||
|
||||
if "\n" not in text and lower.startswith("authorization:"):
|
||||
val = text.split(":", 1)[1].strip()
|
||||
if val.lower().startswith("bearer "):
|
||||
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=val[7:].strip())))
|
||||
else:
|
||||
candidates.append(("Custom Header (Authorization)", MCPAuthConfig(type="headers", headers={"Authorization": val})))
|
||||
return candidates
|
||||
|
||||
# 3. Multiple headers (newline or semicolon separated `Header: Value`)
|
||||
if ("\n" in text or ";" in text) and kv:
|
||||
candidates.append(("Custom Headers", MCPAuthConfig(type="headers", headers=kv)))
|
||||
return candidates
|
||||
|
||||
# 4. Single `Header-Name: value` (with space after colon or header-like left side with `-`)
|
||||
if ":" in text and " " not in text.split(":", 1)[0]:
|
||||
left, right = text.split(":", 1)
|
||||
left_s, right_s = left.strip(), right.strip()
|
||||
if ("-" in left_s or left_s.lower() in ("x-api-key", "apikey", "api-key", "authorization", "x-token", "x-auth-token")) and right_s:
|
||||
candidates.append((f"API Key (header {left_s})", MCPAuthConfig(type="api_key", header_name=left_s, api_key=right_s, api_key_in="header")))
|
||||
candidates.append(("Custom Headers", MCPAuthConfig(type="headers", headers={left_s: right_s})))
|
||||
return candidates
|
||||
# Looks like `username:password`
|
||||
if " " not in text and right_s and not text.startswith(("http://", "https://")):
|
||||
candidates.append(("Basic Auth", MCPAuthConfig(type="basic", username=left_s, password=right_s)))
|
||||
# Also fallback to bearer/api_key in case token itself contains a colon (e.g. `id:secret`)
|
||||
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=text)))
|
||||
candidates.append(("API Key (X-API-Key)", MCPAuthConfig(type="api_key", api_key=text, header_name="X-API-Key", api_key_in="header")))
|
||||
return candidates
|
||||
|
||||
# 5. Single `param=value` or `Header=value`
|
||||
if "=" in text and " " not in text and text.count("=") == 1 and not text.endswith("="):
|
||||
left, right = text.split("=", 1)
|
||||
if left and right and re.match(r"^[A-Za-z][A-Za-z0-9_-]{1,31}$", left):
|
||||
if left.lower() in _QUERY_AUTH_KEYS:
|
||||
candidates.append((f"API Key (query {left})", MCPAuthConfig(type="api_key", api_key=right, query_param=left, api_key_in="query")))
|
||||
candidates.append((f"API Key (header {left})", MCPAuthConfig(type="api_key", api_key=right, header_name=left, api_key_in="header")))
|
||||
else:
|
||||
candidates.append((f"API Key (header {left})", MCPAuthConfig(type="api_key", api_key=right, header_name=left, api_key_in="header")))
|
||||
candidates.append((f"API Key (query {left})", MCPAuthConfig(type="api_key", api_key=right, query_param=left, api_key_in="query")))
|
||||
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=text)))
|
||||
return candidates
|
||||
|
||||
# 6. Plain token / API key -> probe common MCP auth schemes automatically!
|
||||
candidates.extend(
|
||||
[
|
||||
("Bearer Token", MCPAuthConfig(type="bearer", token=text)),
|
||||
("API Key (X-API-Key)", MCPAuthConfig(type="api_key", api_key=text, header_name="X-API-Key", api_key_in="header")),
|
||||
("Authorization: ApiKey", MCPAuthConfig(type="bearer", token=text, token_prefix="ApiKey")),
|
||||
("Authorization: Token", MCPAuthConfig(type="bearer", token=text, token_prefix="Token")),
|
||||
("API Key (query api_key)", MCPAuthConfig(type="api_key", api_key=text, query_param="api_key", api_key_in="query")),
|
||||
]
|
||||
)
|
||||
return candidates
|
||||
|
||||
|
||||
async def smart_apply_credentials_and_probe(
|
||||
manager: MCPConnectorManager,
|
||||
connector_name: str,
|
||||
raw_secret: str,
|
||||
*,
|
||||
discovered_oauth: Optional[dict[str, Any]] = None,
|
||||
hinted_env_vars: Optional[list[str]] = None,
|
||||
) -> SmartProbeResult:
|
||||
"""Automatically detect auth format from raw user credential, probe the MCP server, and save the winner."""
|
||||
state = manager.get_connector(connector_name)
|
||||
if state is None:
|
||||
raise KeyError(f"Коннектор '{connector_name}' не найден.")
|
||||
|
||||
base_cfg = state.config
|
||||
|
||||
# Stdio: update ENV variables and reconnect
|
||||
if base_cfg.transport == "stdio":
|
||||
new_env = dict(base_cfg.env)
|
||||
kv = _parse_kv_multiline(raw_secret)
|
||||
if kv:
|
||||
new_env.update(kv)
|
||||
elif hinted_env_vars:
|
||||
new_env[hinted_env_vars[0]] = raw_secret.strip()
|
||||
else:
|
||||
raise ValueError("Укажите переменную окружения в формате `API_KEY=значение`.")
|
||||
|
||||
updated_cfg = base_cfg.model_copy(update={"env": new_env, "source": "bot"})
|
||||
new_state = await manager.add_or_update_connector(updated_cfg, connect_now=True, persist=True)
|
||||
if new_state.status == "connected":
|
||||
return SmartProbeResult(
|
||||
outcome="connected",
|
||||
state=new_state,
|
||||
detected_auth_label=f"ENV ({', '.join(kv.keys() if kv else hinted_env_vars[:1])})",
|
||||
)
|
||||
return SmartProbeResult(
|
||||
outcome="stdio_error",
|
||||
state=new_state,
|
||||
hinted_env_vars=_extract_hinted_env_vars(new_state.last_error),
|
||||
)
|
||||
|
||||
candidates = _build_credential_candidates(raw_secret, discovered_oauth=discovered_oauth)
|
||||
if not candidates:
|
||||
raise ValueError("Пустые учётные данные.")
|
||||
|
||||
# If candidate is interactive OAuth2 PKCE (with user-supplied client_id), save and start PKCE!
|
||||
if len(candidates) == 1 and candidates[0][1].type == "oauth2_pkce":
|
||||
updated_cfg = base_cfg.model_copy(update={"auth": candidates[0][1], "source": "bot"})
|
||||
await manager.add_or_update_connector(updated_cfg, connect_now=False, persist=True)
|
||||
oauth_info = await manager.start_oauth(base_cfg.name)
|
||||
return SmartProbeResult(
|
||||
outcome="oauth_pkce_ready",
|
||||
state=manager.get_connector(base_cfg.name) or state,
|
||||
oauth_info=oauth_info,
|
||||
detected_auth_label="OAuth 2.1 PKCE",
|
||||
)
|
||||
|
||||
attempts: list[str] = []
|
||||
last_error: Optional[str] = None
|
||||
|
||||
for label, auth_cfg in candidates:
|
||||
attempts.append(label)
|
||||
probe_cfg = base_cfg.model_copy(
|
||||
update={
|
||||
"auth": auth_cfg,
|
||||
"timeout_seconds": min(base_cfg.timeout_seconds, 15),
|
||||
"source": "bot",
|
||||
}
|
||||
)
|
||||
client = MCPClient(probe_cfg, manager.auth_manager)
|
||||
try:
|
||||
await client.connect()
|
||||
await client.list_tools()
|
||||
await client.close()
|
||||
|
||||
# Winner found! Persist with original timeout and connect through manager so tools register cleanly.
|
||||
winning_cfg = base_cfg.model_copy(update={"auth": auth_cfg, "source": "bot"})
|
||||
final_state = await manager.add_or_update_connector(winning_cfg, connect_now=True, persist=True)
|
||||
return SmartProbeResult(
|
||||
outcome="connected",
|
||||
state=final_state,
|
||||
detected_auth_label=label,
|
||||
probe_attempts=attempts,
|
||||
)
|
||||
except (MCPAuthError, MCPAuthRequiredError, MCPProtocolError, Exception) as e:
|
||||
last_error = str(e)
|
||||
await client.close()
|
||||
logger.debug("Smart auth probe '%s' failed for '%s': %s", label, base_cfg.name, e)
|
||||
|
||||
state.last_error = last_error or "Сервер отклонил переданные учётные данные."
|
||||
return SmartProbeResult(
|
||||
outcome="need_credentials",
|
||||
state=state,
|
||||
discovered_oauth=discovered_oauth,
|
||||
probe_attempts=attempts,
|
||||
)
|
||||
@@ -305,6 +305,7 @@ class MCPConnectorManager:
|
||||
state.config = config
|
||||
state.status = "connecting"
|
||||
state.last_error = None
|
||||
state.last_status_code = None
|
||||
state.oauth_challenge = None
|
||||
|
||||
# Close previous client if any
|
||||
@@ -339,6 +340,7 @@ class MCPConnectorManager:
|
||||
state.status = "auth_required"
|
||||
state.tools = []
|
||||
state.last_error = str(e)
|
||||
state.last_status_code = 401
|
||||
state.oauth_challenge = {
|
||||
"www_authenticate": e.www_authenticate,
|
||||
"resource_metadata_url": e.resource_metadata_url,
|
||||
@@ -352,6 +354,7 @@ class MCPConnectorManager:
|
||||
state.status = "error"
|
||||
state.tools = []
|
||||
state.last_error = str(e)
|
||||
state.last_status_code = e.status_code if isinstance(e, MCPProtocolError) else None
|
||||
logger.warning("Failed connecting MCP connector '%s': %s", norm, e)
|
||||
return state
|
||||
|
||||
|
||||
@@ -440,6 +440,7 @@ class MCPConnectorState(BaseModel):
|
||||
protocol_version: Optional[str] = None
|
||||
tools: list[MCPToolInfo] = Field(default_factory=list)
|
||||
last_error: Optional[str] = None
|
||||
last_status_code: Optional[int] = None
|
||||
connected_at: Optional[str] = None
|
||||
oauth_challenge: Optional[dict[str, Any]] = None
|
||||
|
||||
|
||||
Reference in new issue
Block a user