mirror of
https://github.com/zhayujie/chatgpt-on-wechat.git
synced 2026-07-17 11:07:11 +08:00
Compare commits
7 Commits
2.1.3
...
feat-mcp-o
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c7cda89dc | ||
|
|
42a5cf9538 | ||
|
|
996406eb2a | ||
|
|
b98fbae6f6 | ||
|
|
4d87703e31 | ||
|
|
9ef64b7858 | ||
|
|
ed36ca99c0 |
@@ -13,7 +13,7 @@ from agent.tools.utils.diff import (
|
||||
detect_line_ending,
|
||||
normalize_to_lf,
|
||||
restore_line_endings,
|
||||
normalize_for_fuzzy_match,
|
||||
count_matches,
|
||||
fuzzy_find_text,
|
||||
generate_diff_string
|
||||
)
|
||||
@@ -110,10 +110,10 @@ class Edit(BaseTool):
|
||||
"The old text must match exactly including all whitespace and newlines."
|
||||
)
|
||||
|
||||
# Calculate occurrence count (use fuzzy normalized content for consistency)
|
||||
fuzzy_content = normalize_for_fuzzy_match(normalized_content)
|
||||
fuzzy_old_text = normalize_for_fuzzy_match(normalized_old_text)
|
||||
occurrences = fuzzy_content.count(fuzzy_old_text)
|
||||
# Count occurrences with the same matcher used to locate and
|
||||
# replace (fuzzy_find_text), so the uniqueness guard cannot
|
||||
# disagree with what actually gets replaced.
|
||||
occurrences = count_matches(normalized_content, normalized_old_text)
|
||||
|
||||
if occurrences > 1:
|
||||
return ToolResult.fail(
|
||||
|
||||
@@ -21,6 +21,48 @@ from common.log import logger
|
||||
_STREAMABLE_HTTP_ALIASES = {"streamable-http", "streamable_http", "streamablehttp", "http"}
|
||||
|
||||
|
||||
# Optional callback invoked after an OAuth authorization completes, so the
|
||||
# tool manager can bring the newly-authorized server online. Signature:
|
||||
# reload_fn(server_name: str) -> None. Installed by the tool manager.
|
||||
_reload_callback = None
|
||||
|
||||
|
||||
def set_reload_callback(fn) -> None:
|
||||
"""Register a callback fired after a server's OAuth flow succeeds."""
|
||||
global _reload_callback
|
||||
_reload_callback = fn
|
||||
|
||||
|
||||
def notify_server_authorized(server_name: str) -> None:
|
||||
"""Called by the web callback once tokens are stored for a server."""
|
||||
fn = _reload_callback
|
||||
if fn is None:
|
||||
logger.debug(f"[MCP:{server_name}] Authorized but no reload callback registered")
|
||||
return
|
||||
try:
|
||||
fn(server_name)
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP:{server_name}] reload callback failed: {e}")
|
||||
|
||||
|
||||
def _oauth_redirect_uri() -> str:
|
||||
"""Build the OAuth redirect URI served by the web console callback.
|
||||
|
||||
Priority: explicit mcp_oauth_redirect_base config, otherwise the local
|
||||
web console address (127.0.0.1:<web_port>). Both point at the shared
|
||||
/mcp/oauth/callback route.
|
||||
"""
|
||||
try:
|
||||
from config import conf
|
||||
base = (conf().get("mcp_oauth_redirect_base") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
port = int(os.environ.get("COW_WEB_PORT") or conf().get("web_port", 9899))
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
except Exception:
|
||||
base = "http://127.0.0.1:9899"
|
||||
return f"{base}/mcp/oauth/callback"
|
||||
|
||||
|
||||
class McpClient:
|
||||
"""Single MCP Server client supporting stdio, SSE and Streamable HTTP transports."""
|
||||
|
||||
@@ -56,6 +98,13 @@ class McpClient:
|
||||
self._http_headers: dict = {} # extra headers from user config (e.g. Authorization)
|
||||
self._http_session_id: Optional[str] = None # Mcp-Session-Id assigned by the server
|
||||
|
||||
# OAuth state (streamable-http only). Lazily created when the server
|
||||
# responds with 401 and the user has not supplied a static token.
|
||||
self._oauth = None # OAuthHandler instance
|
||||
# Set to True once a 401 could not be satisfied and the user must
|
||||
# complete the browser authorization. Callers can surface this state.
|
||||
self.needs_auth: bool = False
|
||||
|
||||
# Shared state
|
||||
self._next_id = 1
|
||||
self._id_lock = threading.Lock()
|
||||
@@ -325,13 +374,118 @@ class McpClient:
|
||||
if isinstance(extra_headers, dict):
|
||||
self._http_headers = {str(k): str(v) for k, v in extra_headers.items()}
|
||||
|
||||
# Restore any previously stored OAuth credentials for this server so a
|
||||
# restart reuses the token instead of forcing re-authorization.
|
||||
self._maybe_load_oauth()
|
||||
|
||||
return self._handshake()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# OAuth helpers (streamable-http only)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _has_static_auth(self) -> bool:
|
||||
"""True when the user supplied their own Authorization header."""
|
||||
return any(k.lower() == "authorization" for k in self._http_headers)
|
||||
|
||||
def _maybe_load_oauth(self) -> None:
|
||||
"""Attach an OAuthHandler when stored credentials exist for this server."""
|
||||
if self._has_static_auth():
|
||||
return
|
||||
try:
|
||||
from agent.tools.mcp.mcp_oauth import OAuthHandler, load_server_record
|
||||
except Exception:
|
||||
return
|
||||
rec = load_server_record(self.name)
|
||||
# Only create a handler when we have something to reuse; otherwise it
|
||||
# is created lazily on the first 401.
|
||||
if rec.get("access_token") or rec.get("client_id"):
|
||||
self._oauth = OAuthHandler(
|
||||
server_name=self.name,
|
||||
resource_url=self._http_url,
|
||||
redirect_uri=_oauth_redirect_uri(),
|
||||
scope=self.config.get("scope", ""),
|
||||
)
|
||||
|
||||
def _current_bearer(self) -> Optional[str]:
|
||||
"""Return a valid access token, refreshing if needed."""
|
||||
if self._oauth is None:
|
||||
return None
|
||||
return self._oauth.get_valid_access_token()
|
||||
|
||||
def _begin_oauth(self, www_authenticate: str = "") -> None:
|
||||
"""Kick off the OAuth flow after a 401: discover, register, prompt user."""
|
||||
if self._has_static_auth():
|
||||
return
|
||||
try:
|
||||
from agent.tools.mcp.mcp_oauth import OAuthHandler
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP:{self.name}] OAuth module unavailable: {e}")
|
||||
return
|
||||
|
||||
if self._oauth is None:
|
||||
self._oauth = OAuthHandler(
|
||||
server_name=self.name,
|
||||
resource_url=self._http_url,
|
||||
redirect_uri=_oauth_redirect_uri(),
|
||||
scope=self.config.get("scope", ""),
|
||||
)
|
||||
|
||||
if not self._oauth.ensure_registered(www_authenticate):
|
||||
logger.warning(
|
||||
f"[MCP:{self.name}] OAuth discovery/registration failed; "
|
||||
f"cannot authorize automatically"
|
||||
)
|
||||
return
|
||||
|
||||
auth_url = self._oauth.build_authorization_url()
|
||||
if not auth_url:
|
||||
logger.warning(f"[MCP:{self.name}] Failed to build authorization URL")
|
||||
return
|
||||
|
||||
self.needs_auth = True
|
||||
logger.warning(
|
||||
f"[MCP:{self.name}] ⚠️ Authorization required. Open this URL in a "
|
||||
f"browser to authorize, then this server will come online automatically:\n"
|
||||
f" {auth_url}"
|
||||
)
|
||||
# On a machine with a local browser (desktop/dev), open it directly.
|
||||
if os.environ.get("COW_DESKTOP") == "1" or not os.environ.get("COW_HEADLESS"):
|
||||
try:
|
||||
import webbrowser
|
||||
webbrowser.open(auth_url)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _streamable_http_send(self, message: dict) -> dict:
|
||||
"""POST a JSON-RPC request and return the response (JSON or SSE-wrapped)."""
|
||||
return self._streamable_http_post(message, expect_response=True)
|
||||
|
||||
def _streamable_http_post(self, message: dict, expect_response: bool) -> dict:
|
||||
def _handle_401(self, err, message: dict, expect_response: bool, retried: bool) -> dict:
|
||||
"""Handle a 401: refresh the token and retry once, else begin OAuth."""
|
||||
www_auth = ""
|
||||
try:
|
||||
www_auth = err.headers.get("WWW-Authenticate", "") or ""
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
err.read()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# First try a silent refresh with the stored refresh token.
|
||||
if not retried and self._oauth is not None and self._oauth.refresh():
|
||||
logger.info(f"[MCP:{self.name}] Token refreshed after 401, retrying")
|
||||
return self._streamable_http_post(message, expect_response, _retried=True)
|
||||
|
||||
# No usable token — start (or restart) the interactive OAuth flow.
|
||||
self._begin_oauth(www_auth)
|
||||
raise IOError(
|
||||
f"[MCP:{self.name}] streamable-http HTTP 401: authorization required "
|
||||
f"(complete the OAuth flow to enable this server)"
|
||||
)
|
||||
|
||||
def _streamable_http_post(self, message: dict, expect_response: bool, _retried: bool = False) -> dict:
|
||||
"""
|
||||
POST a JSON-RPC message over Streamable HTTP.
|
||||
|
||||
@@ -351,6 +505,12 @@ class McpClient:
|
||||
if sid:
|
||||
headers["Mcp-Session-Id"] = sid
|
||||
headers.update(self._http_headers)
|
||||
# Inject OAuth bearer token when we have one (unless the user set a
|
||||
# static Authorization header, which takes precedence).
|
||||
if not self._has_static_auth():
|
||||
token = self._current_bearer()
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
req = urllib.request.Request(
|
||||
self._http_url,
|
||||
@@ -362,6 +522,9 @@ class McpClient:
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
except urllib.error.HTTPError as e:
|
||||
# 401 is the spec-compliant "needs authorization" signal.
|
||||
if e.code == 401 and not self._has_static_auth():
|
||||
return self._handle_401(e, message, expect_response, _retried)
|
||||
# Surface the server-provided error body for easier debugging
|
||||
detail = ""
|
||||
try:
|
||||
|
||||
466
agent/tools/mcp/mcp_oauth.py
Normal file
466
agent/tools/mcp/mcp_oauth.py
Normal file
@@ -0,0 +1,466 @@
|
||||
"""
|
||||
MCP OAuth 2.1 client (authorization code + PKCE) with zero external deps.
|
||||
|
||||
Implements the subset of the MCP authorization spec needed to connect to
|
||||
remote MCP servers that guard their endpoint behind OAuth (e.g. Xmind):
|
||||
|
||||
1. Metadata discovery via RFC 9728 (protected-resource) + RFC 8414
|
||||
(authorization-server) .well-known documents.
|
||||
2. Dynamic Client Registration (RFC 7591) to obtain a client_id.
|
||||
3. PKCE (RFC 7636, S256) authorization-code flow.
|
||||
4. Token exchange + refresh, persisted to ~/.cow/mcp_oauth.json.
|
||||
|
||||
The actual browser round-trip is completed out-of-band: McpClient generates
|
||||
an authorization URL, the user opens it, and the web console callback
|
||||
(/mcp/oauth/callback) feeds the returned code back into finish_authorization().
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from typing import Optional
|
||||
|
||||
from common.log import logger
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Token store: ~/.cow/mcp_oauth.json {server_name: {...credentials...}}
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
_STORE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _store_path() -> str:
|
||||
base = os.path.expanduser("~/.cow")
|
||||
try:
|
||||
os.makedirs(base, exist_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return os.path.join(base, "mcp_oauth.json")
|
||||
|
||||
|
||||
def _load_store() -> dict:
|
||||
path = _store_path()
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP-OAuth] Failed to read token store: {e}")
|
||||
return {}
|
||||
|
||||
|
||||
def _save_store(store: dict) -> None:
|
||||
path = _store_path()
|
||||
tmp = f"{path}.tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(store, f, ensure_ascii=False, indent=2)
|
||||
os.replace(tmp, path)
|
||||
# Credentials file: restrict to owner read/write when possible.
|
||||
try:
|
||||
os.chmod(path, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP-OAuth] Failed to persist token store: {e}")
|
||||
|
||||
|
||||
def load_server_record(server_name: str) -> dict:
|
||||
with _STORE_LOCK:
|
||||
return dict(_load_store().get(server_name, {}))
|
||||
|
||||
|
||||
def save_server_record(server_name: str, record: dict) -> None:
|
||||
with _STORE_LOCK:
|
||||
store = _load_store()
|
||||
store[server_name] = record
|
||||
_save_store(store)
|
||||
|
||||
|
||||
def clear_server_record(server_name: str) -> None:
|
||||
with _STORE_LOCK:
|
||||
store = _load_store()
|
||||
if server_name in store:
|
||||
store.pop(server_name, None)
|
||||
_save_store(store)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Pending authorizations, keyed by the OAuth `state` param.
|
||||
# Populated when an authorization URL is generated; consumed by the
|
||||
# web callback when the browser redirects back with ?code&state.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
_PENDING_LOCK = threading.Lock()
|
||||
_PENDING: dict = {} # state -> {"handler": OAuthHandler, "created": ts}
|
||||
_PENDING_TTL = 600 # seconds
|
||||
|
||||
|
||||
def _register_pending(state: str, handler: "OAuthHandler") -> None:
|
||||
with _PENDING_LOCK:
|
||||
_prune_pending_locked()
|
||||
_PENDING[state] = {"handler": handler, "created": time.time()}
|
||||
|
||||
|
||||
def _prune_pending_locked() -> None:
|
||||
now = time.time()
|
||||
stale = [s for s, v in _PENDING.items() if now - v["created"] > _PENDING_TTL]
|
||||
for s in stale:
|
||||
_PENDING.pop(s, None)
|
||||
|
||||
|
||||
def pop_pending(state: str) -> Optional["OAuthHandler"]:
|
||||
with _PENDING_LOCK:
|
||||
_prune_pending_locked()
|
||||
entry = _PENDING.pop(state, None)
|
||||
return entry["handler"] if entry else None
|
||||
|
||||
|
||||
def has_pending() -> bool:
|
||||
with _PENDING_LOCK:
|
||||
_prune_pending_locked()
|
||||
return bool(_PENDING)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# HTTP helpers (stdlib only)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
_UA = "CowAgent-MCP-OAuth/1.0"
|
||||
|
||||
|
||||
def _http_get_json(url: str, timeout: int = 15) -> Optional[dict]:
|
||||
req = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": _UA})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read().decode("utf-8")
|
||||
return json.loads(raw)
|
||||
except urllib.error.HTTPError as e:
|
||||
logger.debug(f"[MCP-OAuth] GET {url} -> HTTP {e.code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.debug(f"[MCP-OAuth] GET {url} failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _http_post_form(url: str, fields: dict, timeout: int = 20) -> dict:
|
||||
body = urllib.parse.urlencode(fields).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=body,
|
||||
method="POST",
|
||||
headers={
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Accept": "application/json",
|
||||
"User-Agent": _UA,
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read().decode("utf-8")
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def _http_post_json(url: str, payload: dict, timeout: int = 20) -> dict:
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=body,
|
||||
method="POST",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"User-Agent": _UA,
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read().decode("utf-8")
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Discovery (RFC 9728 + RFC 8414)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _origin(url: str) -> str:
|
||||
p = urllib.parse.urlparse(url)
|
||||
return f"{p.scheme}://{p.netloc}"
|
||||
|
||||
|
||||
def discover_metadata(resource_url: str, www_authenticate: str = "") -> Optional[dict]:
|
||||
"""
|
||||
Resolve the authorization server metadata for a protected MCP resource.
|
||||
|
||||
Returns a dict with at least authorization_endpoint + token_endpoint,
|
||||
plus registration_endpoint when the server supports DCR. Returns None
|
||||
when discovery fails.
|
||||
"""
|
||||
as_metadata_url = _parse_resource_metadata_url(www_authenticate)
|
||||
|
||||
# 1) Protected-resource metadata (RFC 9728) to locate the auth server.
|
||||
auth_server = None
|
||||
prm = None
|
||||
if as_metadata_url:
|
||||
prm = _http_get_json(as_metadata_url)
|
||||
if prm is None:
|
||||
origin = _origin(resource_url)
|
||||
prm = _http_get_json(f"{origin}/.well-known/oauth-protected-resource")
|
||||
if prm and isinstance(prm.get("authorization_servers"), list) and prm["authorization_servers"]:
|
||||
auth_server = prm["authorization_servers"][0]
|
||||
|
||||
# 2) Authorization-server metadata (RFC 8414). Fall back to the resource
|
||||
# origin when the resource did not advertise a separate auth server.
|
||||
base = auth_server or _origin(resource_url)
|
||||
asm = _fetch_as_metadata(base)
|
||||
if not asm:
|
||||
return None
|
||||
|
||||
if not asm.get("authorization_endpoint") or not asm.get("token_endpoint"):
|
||||
logger.warning("[MCP-OAuth] Authorization server metadata missing required endpoints")
|
||||
return None
|
||||
|
||||
# Derive the scope to request. Prefer the resource's required_scopes
|
||||
# (RFC 9728), then its scopes_supported, then the auth server's
|
||||
# scopes_supported. Stored so callers don't have to configure it.
|
||||
discovered_scope = ""
|
||||
if prm:
|
||||
scopes = prm.get("required_scopes") or prm.get("scopes_supported")
|
||||
if isinstance(scopes, list) and scopes:
|
||||
discovered_scope = " ".join(str(s) for s in scopes)
|
||||
if not discovered_scope and isinstance(asm.get("scopes_supported"), list) and asm["scopes_supported"]:
|
||||
discovered_scope = " ".join(str(s) for s in asm["scopes_supported"])
|
||||
if discovered_scope:
|
||||
asm["_discovered_scope"] = discovered_scope
|
||||
return asm
|
||||
|
||||
|
||||
def _parse_resource_metadata_url(www_authenticate: str) -> Optional[str]:
|
||||
"""Extract resource_metadata="..." from a WWW-Authenticate: Bearer header."""
|
||||
if not www_authenticate:
|
||||
return None
|
||||
# naive but sufficient parse for `resource_metadata="URL"`
|
||||
marker = "resource_metadata="
|
||||
idx = www_authenticate.find(marker)
|
||||
if idx < 0:
|
||||
return None
|
||||
rest = www_authenticate[idx + len(marker):].strip()
|
||||
if rest.startswith('"'):
|
||||
end = rest.find('"', 1)
|
||||
return rest[1:end] if end > 0 else None
|
||||
# unquoted, up to comma/space
|
||||
for sep in (",", " "):
|
||||
if sep in rest:
|
||||
rest = rest.split(sep, 1)[0]
|
||||
return rest or None
|
||||
|
||||
|
||||
def _fetch_as_metadata(base: str) -> Optional[dict]:
|
||||
"""Try both RFC 8414 and OIDC well-known locations."""
|
||||
base = base.rstrip("/")
|
||||
candidates = [
|
||||
f"{base}/.well-known/oauth-authorization-server",
|
||||
f"{base}/.well-known/openid-configuration",
|
||||
]
|
||||
for url in candidates:
|
||||
data = _http_get_json(url)
|
||||
if data and data.get("authorization_endpoint"):
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# PKCE
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _b64url(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _make_pkce() -> tuple:
|
||||
verifier = _b64url(secrets.token_bytes(32))
|
||||
challenge = _b64url(hashlib.sha256(verifier.encode("ascii")).digest())
|
||||
return verifier, challenge
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# OAuthHandler: per-server OAuth state machine
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
class OAuthHandler:
|
||||
"""Drives the OAuth flow and token lifecycle for a single MCP server."""
|
||||
|
||||
def __init__(self, server_name: str, resource_url: str, redirect_uri: str,
|
||||
scope: str = "", client_name: str = "CowAgent"):
|
||||
self.server_name = server_name
|
||||
self.resource_url = resource_url
|
||||
self.redirect_uri = redirect_uri
|
||||
self.scope = scope
|
||||
self.client_name = client_name
|
||||
|
||||
rec = load_server_record(server_name)
|
||||
self.metadata: dict = rec.get("metadata", {})
|
||||
self.client_id: Optional[str] = rec.get("client_id")
|
||||
self.client_secret: Optional[str] = rec.get("client_secret")
|
||||
self.access_token: Optional[str] = rec.get("access_token")
|
||||
self.refresh_token: Optional[str] = rec.get("refresh_token")
|
||||
self.expires_at: float = float(rec.get("expires_at", 0) or 0)
|
||||
self._verifier: Optional[str] = None
|
||||
|
||||
# --- persistence -------------------------------------------------
|
||||
|
||||
def _persist(self) -> None:
|
||||
save_server_record(self.server_name, {
|
||||
"resource_url": self.resource_url,
|
||||
"metadata": self.metadata,
|
||||
"client_id": self.client_id,
|
||||
"client_secret": self.client_secret,
|
||||
"access_token": self.access_token,
|
||||
"refresh_token": self.refresh_token,
|
||||
"expires_at": self.expires_at,
|
||||
})
|
||||
|
||||
# --- token access ------------------------------------------------
|
||||
|
||||
def get_valid_access_token(self, leeway: int = 60) -> Optional[str]:
|
||||
"""Return a usable access token, refreshing proactively when near expiry."""
|
||||
if not self.access_token:
|
||||
return None
|
||||
if self.expires_at and time.time() >= self.expires_at - leeway:
|
||||
if not self.refresh():
|
||||
return None
|
||||
return self.access_token
|
||||
|
||||
def refresh(self) -> bool:
|
||||
"""Refresh the access token using the stored refresh token."""
|
||||
if not self.refresh_token or not self.metadata.get("token_endpoint"):
|
||||
return False
|
||||
fields = {
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": self.refresh_token,
|
||||
"client_id": self.client_id or "",
|
||||
}
|
||||
if self.client_secret:
|
||||
fields["client_secret"] = self.client_secret
|
||||
try:
|
||||
resp = _http_post_form(self.metadata["token_endpoint"], fields)
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP-OAuth:{self.server_name}] refresh failed: {e}")
|
||||
return False
|
||||
return self._absorb_token_response(resp)
|
||||
|
||||
# --- authorization-code flow ------------------------------------
|
||||
|
||||
def ensure_registered(self, www_authenticate: str = "") -> bool:
|
||||
"""Discover metadata + register a client if not already done."""
|
||||
if not self.metadata.get("authorization_endpoint"):
|
||||
meta = discover_metadata(self.resource_url, www_authenticate)
|
||||
if not meta:
|
||||
return False
|
||||
self.metadata = meta
|
||||
# Adopt the scope discovered from metadata when the user didn't set one.
|
||||
if not self.scope and self.metadata.get("_discovered_scope"):
|
||||
self.scope = self.metadata["_discovered_scope"]
|
||||
logger.info(f"[MCP-OAuth:{self.server_name}] Using discovered scope: {self.scope}")
|
||||
if not self.client_id:
|
||||
if not self._register_client():
|
||||
return False
|
||||
self._persist()
|
||||
return True
|
||||
|
||||
def _register_client(self) -> bool:
|
||||
reg_endpoint = self.metadata.get("registration_endpoint")
|
||||
if not reg_endpoint:
|
||||
logger.warning(
|
||||
f"[MCP-OAuth:{self.server_name}] No registration_endpoint; "
|
||||
f"DCR unavailable. Provide client_id manually."
|
||||
)
|
||||
return False
|
||||
payload = {
|
||||
"client_name": self.client_name,
|
||||
"redirect_uris": [self.redirect_uri],
|
||||
"grant_types": ["authorization_code", "refresh_token"],
|
||||
"response_types": ["code"],
|
||||
"token_endpoint_auth_method": "none",
|
||||
}
|
||||
if self.scope:
|
||||
payload["scope"] = self.scope
|
||||
try:
|
||||
resp = _http_post_json(reg_endpoint, payload)
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP-OAuth:{self.server_name}] DCR failed: {e}")
|
||||
return False
|
||||
client_id = resp.get("client_id")
|
||||
if not client_id:
|
||||
logger.warning(f"[MCP-OAuth:{self.server_name}] DCR returned no client_id")
|
||||
return False
|
||||
self.client_id = client_id
|
||||
self.client_secret = resp.get("client_secret")
|
||||
logger.info(f"[MCP-OAuth:{self.server_name}] Registered client_id={client_id}")
|
||||
return True
|
||||
|
||||
def build_authorization_url(self) -> Optional[str]:
|
||||
"""Create an authorization URL and register this handler as pending."""
|
||||
if not self.metadata.get("authorization_endpoint") or not self.client_id:
|
||||
return None
|
||||
self._verifier, challenge = _make_pkce()
|
||||
state = secrets.token_urlsafe(24)
|
||||
params = {
|
||||
"response_type": "code",
|
||||
"client_id": self.client_id,
|
||||
"redirect_uri": self.redirect_uri,
|
||||
"code_challenge": challenge,
|
||||
"code_challenge_method": "S256",
|
||||
"state": state,
|
||||
}
|
||||
if self.scope:
|
||||
params["scope"] = self.scope
|
||||
# Advertise the resource we intend to access (RFC 8707).
|
||||
params["resource"] = self.resource_url
|
||||
_register_pending(state, self)
|
||||
return f"{self.metadata['authorization_endpoint']}?{urllib.parse.urlencode(params)}"
|
||||
|
||||
def finish_authorization(self, code: str) -> bool:
|
||||
"""Exchange an authorization code for tokens."""
|
||||
if not self.metadata.get("token_endpoint") or not self._verifier:
|
||||
return False
|
||||
fields = {
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": self.redirect_uri,
|
||||
"client_id": self.client_id or "",
|
||||
"code_verifier": self._verifier,
|
||||
"resource": self.resource_url,
|
||||
}
|
||||
if self.client_secret:
|
||||
fields["client_secret"] = self.client_secret
|
||||
try:
|
||||
resp = _http_post_form(self.metadata["token_endpoint"], fields)
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP-OAuth:{self.server_name}] token exchange failed: {e}")
|
||||
return False
|
||||
ok = self._absorb_token_response(resp)
|
||||
self._verifier = None
|
||||
return ok
|
||||
|
||||
def _absorb_token_response(self, resp: dict) -> bool:
|
||||
access = resp.get("access_token")
|
||||
if not access:
|
||||
logger.warning(f"[MCP-OAuth:{self.server_name}] token response missing access_token: {resp}")
|
||||
return False
|
||||
self.access_token = access
|
||||
if resp.get("refresh_token"):
|
||||
self.refresh_token = resp["refresh_token"]
|
||||
expires_in = resp.get("expires_in")
|
||||
self.expires_at = time.time() + int(expires_in) if expires_in else 0
|
||||
self._persist()
|
||||
logger.info(f"[MCP-OAuth:{self.server_name}] Access token stored")
|
||||
return True
|
||||
@@ -466,21 +466,30 @@ class ToolManager:
|
||||
the others, and never raises out of the worker thread.
|
||||
"""
|
||||
try:
|
||||
from agent.tools.mcp.mcp_client import McpClient, McpClientRegistry
|
||||
from agent.tools.mcp.mcp_client import McpClient, McpClientRegistry, set_reload_callback
|
||||
from agent.tools.mcp.mcp_tool import McpTool
|
||||
|
||||
registry = McpClientRegistry()
|
||||
self._mcp_registry = registry
|
||||
# Let the OAuth web callback bring a server online once authorized.
|
||||
set_reload_callback(self.reload_mcp_server)
|
||||
|
||||
for cfg in mcp_servers_config:
|
||||
server_name = cfg.get("name", "<unnamed>")
|
||||
try:
|
||||
client = McpClient(cfg)
|
||||
if not client.initialize():
|
||||
self._mcp_status[server_name] = "failed"
|
||||
logger.warning(
|
||||
f"[MCP] Server '{server_name}' failed to initialize — skipping"
|
||||
)
|
||||
if getattr(client, "needs_auth", False):
|
||||
self._mcp_status[server_name] = "needs_auth"
|
||||
logger.info(
|
||||
f"[MCP] Server '{server_name}' needs authorization — "
|
||||
f"waiting for the user to complete the OAuth flow"
|
||||
)
|
||||
else:
|
||||
self._mcp_status[server_name] = "failed"
|
||||
logger.warning(
|
||||
f"[MCP] Server '{server_name}' failed to initialize — skipping"
|
||||
)
|
||||
continue
|
||||
|
||||
tool_schemas = client.list_tools()
|
||||
@@ -518,6 +527,28 @@ class ToolManager:
|
||||
except Exception as e:
|
||||
logger.warning(f"[ToolManager] MCP background loader crashed: {e}")
|
||||
|
||||
def reload_mcp_server(self, server_name: str) -> None:
|
||||
"""Re-initialize a single MCP server (e.g. after OAuth authorization).
|
||||
|
||||
Tears down any existing client for the server and starts it again in
|
||||
the background, so a freshly-stored access token is picked up and the
|
||||
server's tools become available on the next message.
|
||||
"""
|
||||
with self._mcp_lock:
|
||||
cfg = self._mcp_active_configs.get(server_name)
|
||||
if not cfg:
|
||||
logger.warning(f"[MCP] reload requested for unknown server '{server_name}'")
|
||||
return
|
||||
logger.info(f"[MCP] Reloading server '{server_name}' after authorization")
|
||||
self._teardown_mcp_server(server_name)
|
||||
self._mcp_status[server_name] = "pending"
|
||||
threading.Thread(
|
||||
target=self._load_mcp_tools_async,
|
||||
args=([cfg],),
|
||||
daemon=True,
|
||||
name=f"mcp-reload-{server_name}",
|
||||
).start()
|
||||
|
||||
def list_mcp_status(self) -> dict:
|
||||
"""Return {server_name: status} snapshot for UI / debugging."""
|
||||
return dict(self._mcp_status)
|
||||
|
||||
@@ -15,6 +15,7 @@ from .diff import (
|
||||
normalize_to_lf,
|
||||
restore_line_endings,
|
||||
normalize_for_fuzzy_match,
|
||||
count_matches,
|
||||
fuzzy_find_text,
|
||||
generate_diff_string,
|
||||
FuzzyMatchResult
|
||||
@@ -39,6 +40,7 @@ __all__ = [
|
||||
'normalize_to_lf',
|
||||
'restore_line_endings',
|
||||
'normalize_for_fuzzy_match',
|
||||
'count_matches',
|
||||
'fuzzy_find_text',
|
||||
'generate_diff_string',
|
||||
'FuzzyMatchResult',
|
||||
|
||||
@@ -93,6 +93,40 @@ class FuzzyMatchResult:
|
||||
self.content_for_replacement = content_for_replacement
|
||||
|
||||
|
||||
def _build_fuzzy_pattern(old_text: str) -> Optional[str]:
|
||||
"""
|
||||
Build the whitespace-flexible regex used to locate ``old_text`` fuzzily.
|
||||
|
||||
Returns ``None`` when ``old_text`` has no non-whitespace content to match.
|
||||
This is the single source of truth for fuzzy matching, so that *finding* a
|
||||
match (:func:`fuzzy_find_text`) and *counting* occurrences
|
||||
(:func:`count_matches`) always use the exact same rules.
|
||||
"""
|
||||
stripped = old_text.strip('\n')
|
||||
if not stripped.strip():
|
||||
return None
|
||||
|
||||
source_lines = stripped.split('\n')
|
||||
line_patterns = []
|
||||
for i, line in enumerate(source_lines):
|
||||
tokens = line.split()
|
||||
if not tokens:
|
||||
line_patterns.append(r'[ \t]*')
|
||||
continue
|
||||
# Tolerate any run of blanks between tokens.
|
||||
core = r'[ \t]+'.join(re.escape(tok) for tok in tokens)
|
||||
# First-line leading whitespace is folded into the match only when
|
||||
# old_text itself was indented here; otherwise it stays OUTSIDE the
|
||||
# match so a no-indent old_text preserves (does not swallow and drop)
|
||||
# the file's existing indentation -- mirroring an exact substring
|
||||
# match. Inner lines always tolerate indentation: it sits inside the
|
||||
# matched region and is re-supplied by new_text.
|
||||
if i > 0 or line[:1] in (' ', '\t'):
|
||||
core = r'[ \t]*' + core
|
||||
line_patterns.append(core + r'[ \t]*')
|
||||
return '\n'.join(line_patterns)
|
||||
|
||||
|
||||
def fuzzy_find_text(content: str, old_text: str) -> FuzzyMatchResult:
|
||||
"""
|
||||
Find text in content, try exact match first, then fuzzy match
|
||||
@@ -110,7 +144,7 @@ def fuzzy_find_text(content: str, old_text: str) -> FuzzyMatchResult:
|
||||
match_length=len(old_text),
|
||||
content_for_replacement=content
|
||||
)
|
||||
|
||||
|
||||
# Fuzzy match: the exact substring was not found, most likely because the
|
||||
# whitespace differs (indentation, spaces around operators, trailing
|
||||
# spaces). Locate the region in the ORIGINAL content using a
|
||||
@@ -121,27 +155,8 @@ def fuzzy_find_text(content: str, old_text: str) -> FuzzyMatchResult:
|
||||
# doing so previously returned the normalized copy as
|
||||
# content_for_replacement, which caused the whole file to be rewritten
|
||||
# with collapsed indentation (every untouched line got reformatted).
|
||||
stripped = old_text.strip('\n')
|
||||
if stripped.strip():
|
||||
source_lines = stripped.split('\n')
|
||||
line_patterns = []
|
||||
for i, line in enumerate(source_lines):
|
||||
tokens = line.split()
|
||||
if not tokens:
|
||||
line_patterns.append(r'[ \t]*')
|
||||
continue
|
||||
# Tolerate any run of blanks between tokens.
|
||||
core = r'[ \t]+'.join(re.escape(tok) for tok in tokens)
|
||||
# First-line leading whitespace is folded into the match only when
|
||||
# old_text itself was indented here; otherwise it stays OUTSIDE the
|
||||
# match so a no-indent old_text preserves (does not swallow and drop)
|
||||
# the file's existing indentation -- mirroring an exact substring
|
||||
# match. Inner lines always tolerate indentation: it sits inside the
|
||||
# matched region and is re-supplied by new_text.
|
||||
if i > 0 or line[:1] in (' ', '\t'):
|
||||
core = r'[ \t]*' + core
|
||||
line_patterns.append(core + r'[ \t]*')
|
||||
pattern = '\n'.join(line_patterns)
|
||||
pattern = _build_fuzzy_pattern(old_text)
|
||||
if pattern is not None:
|
||||
match = re.search(pattern, content)
|
||||
if match:
|
||||
return FuzzyMatchResult(
|
||||
@@ -155,6 +170,28 @@ def fuzzy_find_text(content: str, old_text: str) -> FuzzyMatchResult:
|
||||
return FuzzyMatchResult(found=False)
|
||||
|
||||
|
||||
def count_matches(content: str, old_text: str) -> int:
|
||||
"""
|
||||
Count occurrences of ``old_text`` using the SAME strategy as
|
||||
:func:`fuzzy_find_text`: an exact substring when one is present, otherwise
|
||||
the whitespace-flexible fuzzy regex.
|
||||
|
||||
The edit tool's uniqueness guard must agree with the matcher that actually
|
||||
performs the replacement. Counting through a separate normalization pass
|
||||
(the previous approach) could disagree with the regex used to locate and
|
||||
replace, so both paths now share :func:`_build_fuzzy_pattern`.
|
||||
"""
|
||||
if not old_text:
|
||||
return 0
|
||||
# Mirror fuzzy_find_text: prefer exact matching when it applies.
|
||||
if content.find(old_text) != -1:
|
||||
return content.count(old_text)
|
||||
pattern = _build_fuzzy_pattern(old_text)
|
||||
if pattern is None:
|
||||
return 0
|
||||
return len(re.findall(pattern, content))
|
||||
|
||||
|
||||
def generate_diff_string(old_content: str, new_content: str) -> dict:
|
||||
"""
|
||||
Generate unified diff string
|
||||
|
||||
@@ -79,11 +79,42 @@ def _verify_auth_token(token):
|
||||
return hmac.compare_digest(sig, expected)
|
||||
|
||||
|
||||
def _get_bearer_token():
|
||||
"""Extract the token from an `Authorization: Bearer <token>` header.
|
||||
|
||||
The desktop client renders from a file:// origin, so cross-origin cookies
|
||||
to http://127.0.0.1 are unreliable (SameSite=Lax cookies aren't sent). It
|
||||
therefore authenticates via this header instead; browsers keep using the
|
||||
cookie set by /auth/login.
|
||||
"""
|
||||
auth = web.ctx.env.get("HTTP_AUTHORIZATION", "") or ""
|
||||
if auth.startswith("Bearer "):
|
||||
return auth[7:].strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _get_query_token():
|
||||
"""Extract a token from the `token` query param.
|
||||
|
||||
Needed for SSE endpoints: EventSource can't set an Authorization header,
|
||||
and file:// cookies are unreliable, so the desktop client passes the token
|
||||
in the query string for /stream and /api/logs.
|
||||
"""
|
||||
try:
|
||||
return web.input(token="").token or ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _check_auth():
|
||||
"""Return True if request is authenticated or password not enabled."""
|
||||
if not _is_password_enabled():
|
||||
return True
|
||||
return _verify_auth_token(web.cookies().get("cow_auth_token", ""))
|
||||
if _verify_auth_token(web.cookies().get("cow_auth_token", "")):
|
||||
return True
|
||||
if _verify_auth_token(_get_bearer_token()):
|
||||
return True
|
||||
return _verify_auth_token(_get_query_token())
|
||||
|
||||
|
||||
def _require_auth():
|
||||
@@ -1249,6 +1280,7 @@ class WebChannel(ChatChannel):
|
||||
|
||||
urls = (
|
||||
'/', 'RootHandler',
|
||||
'/api/health', 'HealthHandler',
|
||||
'/auth/login', 'AuthLoginHandler',
|
||||
'/auth/check', 'AuthCheckHandler',
|
||||
'/auth/logout', 'AuthLogoutHandler',
|
||||
@@ -1288,6 +1320,7 @@ class WebChannel(ChatChannel):
|
||||
'/api/messages/delete', 'MessageDeleteHandler',
|
||||
'/api/logs', 'LogsHandler',
|
||||
'/api/version', 'VersionHandler',
|
||||
'/mcp/oauth/callback', 'McpOAuthCallbackHandler',
|
||||
'/assets/(.*)', 'AssetsHandler',
|
||||
)
|
||||
app = web.application(urls, globals(), autoreload=False)
|
||||
@@ -1341,6 +1374,74 @@ class RootHandler:
|
||||
raise web.seeother('/chat')
|
||||
|
||||
|
||||
class HealthHandler:
|
||||
# Unauthenticated liveness probe. The desktop shell polls this to know the
|
||||
# backend is up; it must never require auth (a set web_password would
|
||||
# otherwise make startup hang). Returns no sensitive data.
|
||||
def GET(self):
|
||||
web.header('Content-Type', 'application/json; charset=utf-8')
|
||||
web.header('Cache-Control', 'no-store')
|
||||
return json.dumps({"status": "ok"})
|
||||
|
||||
|
||||
class McpOAuthCallbackHandler:
|
||||
"""OAuth redirect target for MCP servers requiring authorization.
|
||||
|
||||
The browser lands here after the user authorizes a remote MCP server.
|
||||
We exchange the authorization code for tokens and bring the server
|
||||
online. Unauthenticated by design: the OAuth `state` param is the
|
||||
single-use secret that binds this request to a pending authorization.
|
||||
"""
|
||||
|
||||
def GET(self):
|
||||
web.header('Content-Type', 'text/html; charset=utf-8')
|
||||
params = web.input(code="", state="", error="", error_description="")
|
||||
|
||||
def _page(title: str, message: str) -> str:
|
||||
return (
|
||||
"<!doctype html><html><head><meta charset='utf-8'>"
|
||||
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
|
||||
f"<title>{title}</title></head>"
|
||||
"<body style='font-family:-apple-system,Segoe UI,Roboto,sans-serif;"
|
||||
"max-width:520px;margin:64px auto;padding:0 20px;text-align:center;color:#1f2328'>"
|
||||
f"<h2>{title}</h2><p style='color:#57606a'>{message}</p></body></html>"
|
||||
)
|
||||
|
||||
if params.error:
|
||||
logger.warning(f"[MCP-OAuth] callback error: {params.error} {params.error_description}")
|
||||
return _page("授权失败", f"{params.error}: {params.error_description or ''}")
|
||||
|
||||
if not params.code or not params.state:
|
||||
return _page("参数缺失", "回调缺少 code 或 state 参数。")
|
||||
|
||||
try:
|
||||
from agent.tools.mcp.mcp_oauth import pop_pending
|
||||
from agent.tools.mcp.mcp_client import notify_server_authorized
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP-OAuth] callback import failed: {e}")
|
||||
return _page("内部错误", "OAuth 模块不可用。")
|
||||
|
||||
handler = pop_pending(params.state)
|
||||
if handler is None:
|
||||
return _page("会话已过期", "授权请求不存在或已过期,请重新触发授权。")
|
||||
|
||||
try:
|
||||
ok = handler.finish_authorization(params.code)
|
||||
except Exception as e:
|
||||
logger.warning(f"[MCP-OAuth] token exchange crashed: {e}")
|
||||
ok = False
|
||||
|
||||
if not ok:
|
||||
return _page("授权失败", "换取令牌失败,请重试。")
|
||||
|
||||
notify_server_authorized(handler.server_name)
|
||||
logger.info(f"[MCP-OAuth] Server '{handler.server_name}' authorized via web callback")
|
||||
return _page(
|
||||
"授权成功",
|
||||
f"MCP 服务 “{handler.server_name}” 已授权,可以返回聊天继续使用了。",
|
||||
)
|
||||
|
||||
|
||||
class AuthCheckHandler:
|
||||
def GET(self):
|
||||
web.header('Content-Type', 'application/json; charset=utf-8')
|
||||
@@ -1368,7 +1469,9 @@ class AuthLoginHandler:
|
||||
token = _create_auth_token()
|
||||
web.setcookie("cow_auth_token", token, expires=_session_expire_seconds(),
|
||||
path="/", httponly=True, samesite="Lax")
|
||||
return json.dumps({"status": "success"})
|
||||
# Also return the token in the body: the desktop client (file:// origin)
|
||||
# can't rely on the cookie and sends it back via an Authorization header.
|
||||
return json.dumps({"status": "success", "token": token})
|
||||
|
||||
|
||||
class AuthLogoutHandler:
|
||||
@@ -1807,7 +1910,7 @@ class ConfigHandler:
|
||||
raw_pwd = str(local_config.get("web_password", "") or "")
|
||||
masked_pwd = ("*" * len(raw_pwd)) if raw_pwd else ""
|
||||
|
||||
return json.dumps({
|
||||
result = {
|
||||
"status": "success",
|
||||
"use_agent": use_agent,
|
||||
"title": title,
|
||||
@@ -1824,7 +1927,13 @@ class ConfigHandler:
|
||||
"api_keys": api_keys_masked,
|
||||
"providers": providers,
|
||||
"web_password_masked": masked_pwd,
|
||||
}, ensure_ascii=False)
|
||||
}
|
||||
# The desktop app runs on the local trusted machine, so it can edit
|
||||
# the real password in place (cursor at the end, delete to clear).
|
||||
# Browser access only ever sees the masked value.
|
||||
if os.environ.get("COW_DESKTOP") == "1":
|
||||
result["web_password"] = raw_pwd
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting config: {e}")
|
||||
return json.dumps({"status": "error", "message": str(e)})
|
||||
|
||||
@@ -253,6 +253,7 @@ available_setting = {
|
||||
"web_password": "", # Web console password; empty means no authentication required
|
||||
"web_session_expire_days": 30, # Auth session expiry in days
|
||||
"web_file_serve_root": "~", # Root dir the /api/file endpoint may serve; "/" allows the whole filesystem
|
||||
"mcp_oauth_redirect_base": "", # Base URL for MCP OAuth callback (e.g. http://your-ip:9899); empty uses local web console
|
||||
"agent": True, # whether to enable Agent mode
|
||||
"agent_workspace": "~/cow", # agent workspace path, used to store skills, memory, etc.
|
||||
"agent_max_context_tokens": 50000, # max context tokens in Agent mode
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ChildProcess, spawn } from 'child_process'
|
||||
import { ChildProcess, spawn, execFileSync } from 'child_process'
|
||||
import { EventEmitter } from 'events'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
@@ -39,6 +39,77 @@ export class PythonBackend extends EventEmitter {
|
||||
return this.status
|
||||
}
|
||||
|
||||
// Cache the resolved PATH so we only spawn a login shell once per process.
|
||||
private resolvedPath: string | null = null
|
||||
|
||||
/**
|
||||
* Build the PATH the backend should run with.
|
||||
*
|
||||
* When launched from Finder/Dock, a GUI app inherits launchd's minimal PATH
|
||||
* (/usr/bin:/bin:...) and never loads ~/.zshrc, so user-installed CLIs like
|
||||
* `linkai`, `node`, or Homebrew tools are invisible to the agent's bash tool.
|
||||
* We recover the real login-shell PATH (macOS/Linux) and merge in common bin
|
||||
* dirs, so the agent can find these commands regardless of how the app started.
|
||||
*/
|
||||
private resolveEnvPath(): string {
|
||||
if (this.resolvedPath !== null) {
|
||||
return this.resolvedPath
|
||||
}
|
||||
|
||||
const sep = path.delimiter
|
||||
const existing = process.env.PATH || ''
|
||||
const parts: string[] = existing ? existing.split(sep) : []
|
||||
|
||||
// Windows GUI apps already inherit the full system PATH; nothing to fix.
|
||||
if (process.platform !== 'win32') {
|
||||
// Ask the user's login shell for its PATH. `-ilc` runs an interactive
|
||||
// login shell so it sources ~/.zshrc / ~/.zprofile etc.
|
||||
try {
|
||||
const shell = process.env.SHELL || '/bin/zsh'
|
||||
const out = execFileSync(shell, ['-ilc', 'echo -n "__PATH__$PATH"'], {
|
||||
encoding: 'utf8',
|
||||
timeout: 5000,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
const marker = out.lastIndexOf('__PATH__')
|
||||
if (marker !== -1) {
|
||||
const shellPath = out.slice(marker + '__PATH__'.length).trim()
|
||||
if (shellPath) {
|
||||
parts.push(...shellPath.split(sep))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Shell probe failed (unusual shell, timeout). Fall back to the
|
||||
// common dirs below so at least the typical install paths work.
|
||||
}
|
||||
|
||||
const home = os.homedir()
|
||||
parts.push(
|
||||
path.join(home, '.local/bin'),
|
||||
'/usr/local/bin',
|
||||
'/opt/homebrew/bin',
|
||||
'/usr/bin',
|
||||
'/bin',
|
||||
'/usr/sbin',
|
||||
'/sbin',
|
||||
)
|
||||
}
|
||||
|
||||
// De-duplicate while preserving order (first occurrence wins).
|
||||
const seen = new Set<string>()
|
||||
const merged: string[] = []
|
||||
for (const p of parts) {
|
||||
const dir = p.trim()
|
||||
if (dir && !seen.has(dir)) {
|
||||
seen.add(dir)
|
||||
merged.push(dir)
|
||||
}
|
||||
}
|
||||
|
||||
this.resolvedPath = merged.join(sep)
|
||||
return this.resolvedPath
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the packaged onedir backend executable shipped with the app.
|
||||
* Returns null when not present (e.g. during local development), so we can
|
||||
@@ -261,6 +332,10 @@ export class PythonBackend extends EventEmitter {
|
||||
// app bundle stays read-only; dev runs omit it and keep using the repo.
|
||||
env: {
|
||||
...process.env,
|
||||
// Recover the user's real PATH (login shell + common bin dirs) so the
|
||||
// agent's bash tool can find CLIs like `linkai`/`node` even when the
|
||||
// app is launched from Finder/Dock with launchd's minimal PATH.
|
||||
PATH: this.resolveEnvPath(),
|
||||
PYTHONUNBUFFERED: '1',
|
||||
COW_DESKTOP: '1',
|
||||
// The shell owns the port: tell the backend to bind exactly here so the
|
||||
@@ -315,7 +390,10 @@ export class PythonBackend extends EventEmitter {
|
||||
const startedAt = Date.now()
|
||||
|
||||
const check = () => {
|
||||
const req = http.get(`http://127.0.0.1:${this.port}/config`, (res) => {
|
||||
// Probe the unauthenticated health endpoint, NOT /config: /config
|
||||
// requires auth once a web_password is set, which would make this poll
|
||||
// 401 forever and hang startup.
|
||||
const req = http.get(`http://127.0.0.1:${this.port}/api/health`, (res) => {
|
||||
if (res.statusCode === 200) {
|
||||
this.status = 'ready'
|
||||
this.emit('log', `Backend ready on port ${this.port}`)
|
||||
|
||||
@@ -5,6 +5,7 @@ import NavRail from './layout/NavRail'
|
||||
import SessionList from './layout/SessionList'
|
||||
import WindowControls from './layout/WindowControls'
|
||||
import StatusScreen from './components/StatusScreen'
|
||||
import LoginGate from './components/LoginGate'
|
||||
import { useBackend } from './hooks/useBackend'
|
||||
import { usePlatform } from './hooks/usePlatform'
|
||||
import { useUIStore } from './store/uiStore'
|
||||
@@ -32,16 +33,45 @@ const App: React.FC = () => {
|
||||
const onboardingOpen = useOnboardingStore((s) => s.open)
|
||||
const maybeOpenOnboarding = useOnboardingStore((s) => s.maybeOpen)
|
||||
const [, forceUpdate] = useState(0)
|
||||
// Auth gate for web_password-protected backends. 'checking' until we know
|
||||
// whether login is needed; 'need_login' shows the password screen; 'ok' lets
|
||||
// the main UI render.
|
||||
const [authState, setAuthState] = useState<'checking' | 'need_login' | 'ok'>('checking')
|
||||
|
||||
useEffect(() => {
|
||||
if (backend.status === 'ready') apiClient.setBaseUrl(backend.baseUrl)
|
||||
}, [backend.status, backend.baseUrl])
|
||||
|
||||
// Once the backend is ready, check whether a web_password is set. If so and
|
||||
// this session isn't authenticated, show the login gate before the app.
|
||||
useEffect(() => {
|
||||
if (backend.status !== 'ready') {
|
||||
setAuthState('checking')
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
apiClient
|
||||
.authCheck()
|
||||
.then((res) => {
|
||||
if (cancelled) return
|
||||
const needLogin = res.auth_required && !res.authenticated
|
||||
setAuthState(needLogin ? 'need_login' : 'ok')
|
||||
})
|
||||
.catch(() => {
|
||||
// If the check itself fails, don't hard-block the user — assume no auth
|
||||
// is required (backends without web_password never return errors here).
|
||||
if (!cancelled) setAuthState('ok')
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [backend.status, backend.baseUrl])
|
||||
|
||||
// First-run check: once the backend is ready, decide whether to show the
|
||||
// onboarding wizard. It's config-driven — shown whenever the chat model isn't
|
||||
// configured (and not dismissed earlier this session); no persisted flag.
|
||||
useEffect(() => {
|
||||
if (backend.status !== 'ready') return
|
||||
if (backend.status !== 'ready' || authState !== 'ok') return
|
||||
let cancelled = false
|
||||
apiClient
|
||||
.getModels()
|
||||
@@ -65,7 +95,7 @@ const App: React.FC = () => {
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [backend.status, maybeOpenOnboarding])
|
||||
}, [backend.status, authState, maybeOpenOnboarding])
|
||||
|
||||
// Subscribe to auto-update status from the main process (no-op in dev).
|
||||
useEffect(() => initUpdateListener(), [])
|
||||
@@ -91,6 +121,15 @@ const App: React.FC = () => {
|
||||
return <StatusScreen status={backend.status} error={backend.error} onRetry={backend.restart} />
|
||||
}
|
||||
|
||||
// Backend is up but we're still resolving auth — keep the loading screen.
|
||||
if (authState === 'checking') {
|
||||
return <StatusScreen status="connecting" onRetry={backend.restart} />
|
||||
}
|
||||
|
||||
if (authState === 'need_login') {
|
||||
return <LoginGate onAuthenticated={() => setAuthState('ok')} />
|
||||
}
|
||||
|
||||
const isChat = location.pathname === '/'
|
||||
const showSessions = isChat && !sessionsCollapsed
|
||||
|
||||
|
||||
@@ -24,8 +24,16 @@ interface ApiResult {
|
||||
message?: string
|
||||
}
|
||||
|
||||
const AUTH_TOKEN_KEY = 'cow_auth_token'
|
||||
|
||||
class ApiClient {
|
||||
private baseUrl = 'http://127.0.0.1:9876'
|
||||
// Bearer token for web_password-protected backends. The desktop renderer
|
||||
// runs from a file:// origin, where cross-origin cookies to http://127.0.0.1
|
||||
// aren't sent reliably, so we authenticate via an Authorization header
|
||||
// instead. Persisted in localStorage so it survives reloads.
|
||||
private authToken: string | null =
|
||||
typeof localStorage !== 'undefined' ? localStorage.getItem(AUTH_TOKEN_KEY) : null
|
||||
|
||||
setBaseUrl(url: string) {
|
||||
this.baseUrl = url
|
||||
@@ -35,13 +43,25 @@ class ApiClient {
|
||||
return this.baseUrl
|
||||
}
|
||||
|
||||
setAuthToken(token: string | null) {
|
||||
this.authToken = token
|
||||
try {
|
||||
if (token) localStorage.setItem(AUTH_TOKEN_KEY, token)
|
||||
else localStorage.removeItem(AUTH_TOKEN_KEY)
|
||||
} catch {
|
||||
// localStorage may be unavailable; in-memory token still works this session
|
||||
}
|
||||
}
|
||||
|
||||
private async request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${this.baseUrl}${path}`, {
|
||||
...options,
|
||||
// Send cookies for future web_password auth support
|
||||
// Cookies still work for browser access; the desktop app relies on the
|
||||
// Authorization header below.
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(this.authToken ? { Authorization: `Bearer ${this.authToken}` } : {}),
|
||||
...options?.headers,
|
||||
},
|
||||
})
|
||||
@@ -93,8 +113,16 @@ class ApiClient {
|
||||
})
|
||||
}
|
||||
|
||||
// EventSource can't set an Authorization header, so append the auth token as
|
||||
// a query param for SSE endpoints (the backend accepts it there).
|
||||
private withToken(url: string): string {
|
||||
if (!this.authToken) return url
|
||||
const sep = url.includes('?') ? '&' : '?'
|
||||
return `${url}${sep}token=${encodeURIComponent(this.authToken)}`
|
||||
}
|
||||
|
||||
createSSEStream(requestId: string): EventSource {
|
||||
return new EventSource(`${this.baseUrl}/stream?request_id=${requestId}`)
|
||||
return new EventSource(this.withToken(`${this.baseUrl}/stream?request_id=${requestId}`))
|
||||
}
|
||||
|
||||
async deleteMessage(opts: {
|
||||
@@ -138,11 +166,13 @@ class ApiClient {
|
||||
|
||||
getFileUrl(previewUrl: string): string {
|
||||
if (/^https?:\/\//.test(previewUrl)) return previewUrl
|
||||
return `${this.baseUrl}${previewUrl}`
|
||||
// Served via <img src>, which can't set headers — carry the token in the
|
||||
// query so protected file endpoints load under web_password.
|
||||
return this.withToken(`${this.baseUrl}${previewUrl}`)
|
||||
}
|
||||
|
||||
getServeFileUrl(absPath: string): string {
|
||||
return `${this.baseUrl}/api/file?path=${encodeURIComponent(absPath)}`
|
||||
return this.withToken(`${this.baseUrl}/api/file?path=${encodeURIComponent(absPath)}`)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------
|
||||
@@ -390,7 +420,7 @@ class ApiClient {
|
||||
// ---------------------------------------------------------
|
||||
|
||||
createLogStream(): EventSource {
|
||||
return new EventSource(`${this.baseUrl}/api/logs`)
|
||||
return new EventSource(this.withToken(`${this.baseUrl}/api/logs`))
|
||||
}
|
||||
|
||||
async getVersion(): Promise<string> {
|
||||
@@ -406,14 +436,19 @@ class ApiClient {
|
||||
return this.request('/auth/check')
|
||||
}
|
||||
|
||||
async authLogin(password: string): Promise<ApiResult> {
|
||||
return this.request('/auth/login', {
|
||||
async authLogin(password: string): Promise<ApiResult & { token?: string }> {
|
||||
const res = await this.request<ApiResult & { token?: string }>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password }),
|
||||
})
|
||||
if (res.status === 'success' && res.token) {
|
||||
this.setAuthToken(res.token)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
async authLogout(): Promise<ApiResult> {
|
||||
this.setAuthToken(null)
|
||||
return this.request('/auth/logout', { method: 'POST' })
|
||||
}
|
||||
}
|
||||
|
||||
72
desktop/src/renderer/src/components/LoginGate.tsx
Normal file
72
desktop/src/renderer/src/components/LoginGate.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import React, { useState } from 'react'
|
||||
import apiClient from '../api/client'
|
||||
import { t } from '../i18n'
|
||||
|
||||
interface LoginGateProps {
|
||||
// Called once the password is accepted (auth cookie set), so the app can
|
||||
// proceed to the main UI.
|
||||
onAuthenticated: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown when the backend has a web_password set and the current session isn't
|
||||
* authenticated yet. Submitting the correct password sets an auth cookie
|
||||
* (handled by the backend), after which the app reloads its data.
|
||||
*/
|
||||
const LoginGate: React.FC<LoginGateProps> = ({ onAuthenticated }) => {
|
||||
const [password, setPassword] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!password || submitting) return
|
||||
setSubmitting(true)
|
||||
setError('')
|
||||
try {
|
||||
const res = await apiClient.authLogin(password)
|
||||
if (res.status === 'success') {
|
||||
onAuthenticated()
|
||||
} else {
|
||||
setError(t('login_error'))
|
||||
}
|
||||
} catch {
|
||||
setError(t('login_error'))
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-screen w-screen flex items-center justify-center bg-gray-50 dark:bg-[#111111]">
|
||||
<form onSubmit={submit} className="text-center space-y-6 max-w-md px-8 w-full">
|
||||
<img src="./logo.jpg" alt="CowAgent" className="w-16 h-16 rounded-2xl mx-auto shadow-lg shadow-primary-500/20" />
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-bold text-slate-800 dark:text-slate-100">{t('login_title')}</h1>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">{t('login_desc')}</p>
|
||||
</div>
|
||||
<input
|
||||
type="password"
|
||||
autoFocus
|
||||
value={password}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value)
|
||||
if (error) setError('')
|
||||
}}
|
||||
placeholder={t('login_placeholder')}
|
||||
className="w-full px-4 py-2.5 rounded-lg border border-slate-300 dark:border-slate-700 bg-white dark:bg-[#1a1a1a] text-slate-800 dark:text-slate-100 text-sm outline-none focus:border-primary-500 transition-colors"
|
||||
/>
|
||||
{error && <p className="text-sm text-red-500">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting || !password}
|
||||
className="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-primary-500 hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-colors text-sm font-medium cursor-pointer"
|
||||
>
|
||||
{submitting ? t('login_checking') : t('login_submit')}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoginGate
|
||||
@@ -22,7 +22,10 @@ export function useBackend() {
|
||||
|
||||
const probeBackend = useCallback(async (port: number): Promise<boolean> => {
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${port}/config`, {
|
||||
// Probe the unauthenticated health endpoint, NOT /config: once a
|
||||
// web_password is set, /config returns 401 and we'd wrongly treat the
|
||||
// (healthy) backend as unreachable, hanging on "connecting".
|
||||
const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
})
|
||||
return res.ok
|
||||
|
||||
@@ -356,6 +356,13 @@ const translations: Record<string, Record<string, string>> = {
|
||||
status_error: '初始化失败',
|
||||
status_error_desc: '客户端初始化失败,请重试',
|
||||
status_retry: '重试',
|
||||
// login (web_password)
|
||||
login_title: '请输入访问密码',
|
||||
login_desc: '此客户端已设置访问密码,请输入以继续',
|
||||
login_placeholder: '访问密码',
|
||||
login_submit: '进入',
|
||||
login_error: '密码错误,请重试',
|
||||
login_checking: '验证中...',
|
||||
// slash command descriptions
|
||||
slash_menu_title: '命令',
|
||||
slash_new: '新建对话',
|
||||
@@ -731,6 +738,13 @@ const translations: Record<string, Record<string, string>> = {
|
||||
status_error: 'Initialization Failed',
|
||||
status_error_desc: 'Failed to initialize the client, please retry',
|
||||
status_retry: 'Retry',
|
||||
// login (web_password)
|
||||
login_title: 'Enter access password',
|
||||
login_desc: 'This client is password-protected. Enter the password to continue.',
|
||||
login_placeholder: 'Access password',
|
||||
login_submit: 'Enter',
|
||||
login_error: 'Wrong password, please try again',
|
||||
login_checking: 'Verifying...',
|
||||
// slash command descriptions
|
||||
slash_menu_title: 'Commands',
|
||||
slash_new: 'New chat',
|
||||
|
||||
@@ -55,7 +55,9 @@ const BasicSettings: React.FC<BasicSettingsProps> = ({ baseUrl, onLangChange, on
|
||||
setMaxSteps(data.agent_max_steps ?? 20)
|
||||
setThinking(!!data.enable_thinking)
|
||||
setEvolution(!!data.self_evolution_enabled)
|
||||
setPassword(data.web_password_masked || '')
|
||||
// Prefer the real password (desktop only) so it can be edited in place;
|
||||
// fall back to the masked value for browser access.
|
||||
setPassword(data.web_password ?? data.web_password_masked ?? '')
|
||||
setPwDirty(false)
|
||||
|
||||
const ids = data.providers ? Object.keys(data.providers) : []
|
||||
@@ -130,8 +132,14 @@ const BasicSettings: React.FC<BasicSettingsProps> = ({ baseUrl, onLangChange, on
|
||||
setTimeout(() => setAgentStatus(''), 2000)
|
||||
}
|
||||
|
||||
// Desktop returns the real password, so the field holds plaintext and can be
|
||||
// saved (including cleared) directly. Browser access only has the masked
|
||||
// value, where a masked string must never be saved as the real password.
|
||||
const hasRealPassword = config?.web_password !== undefined
|
||||
|
||||
const savePassword = async () => {
|
||||
if (!pwDirty || MASK_RE.test(password)) return
|
||||
if (!pwDirty) return
|
||||
if (!hasRealPassword && MASK_RE.test(password)) return
|
||||
try {
|
||||
await apiClient.updateConfig({ web_password: password })
|
||||
setPwStatus(password ? t('config_password_saved') : t('config_password_cleared'))
|
||||
@@ -292,10 +300,13 @@ const BasicSettings: React.FC<BasicSettingsProps> = ({ baseUrl, onLangChange, on
|
||||
value={password}
|
||||
placeholder={t('config_password_placeholder')}
|
||||
onFocus={() => {
|
||||
if (!pwDirty && MASK_RE.test(password)) setPassword('')
|
||||
// Browser access shows a mask; clear it on focus so the user
|
||||
// types a fresh password. Desktop holds the real password and
|
||||
// must stay editable in place (cursor at the end).
|
||||
if (!hasRealPassword && !pwDirty && MASK_RE.test(password)) setPassword('')
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (!pwDirty) setPassword(config?.web_password_masked || '')
|
||||
if (!hasRealPassword && !pwDirty) setPassword(config?.web_password_masked || '')
|
||||
}}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value)
|
||||
|
||||
@@ -230,6 +230,9 @@ export interface ConfigData {
|
||||
api_keys: Record<string, string>
|
||||
providers: Record<string, ProviderMeta>
|
||||
web_password_masked?: string
|
||||
// Real password, only returned to the desktop app (trusted local machine) so
|
||||
// it can be edited in place. Undefined for browser access.
|
||||
web_password?: string
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
|
||||
@@ -5,6 +5,8 @@ description: Download and use the CowAgent desktop client (macOS / Windows)
|
||||
|
||||
CowAgent ships a ready-to-use desktop client with the Agent runtime bundled in — **no need to install Python or dependencies manually**. Just download, install, and run your local super AI assistant.
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/desktop-chat-demo-en.png" alt="CowAgent Desktop client" />
|
||||
|
||||
## Download & Install
|
||||
|
||||
<Card title="Go to the download page" icon="download" href="https://cowagent.ai/download/">
|
||||
@@ -34,3 +36,16 @@ The desktop client has built-in auto-update. When a new version is available it
|
||||
|
||||
- **Desktop client**: best for personal use on your own computer — works out of the box, GUI-based, auto-updating.
|
||||
- **Command-line deployment**: best for developers or long-running servers with more customization. See [Quick Start](/guide/quick-start).
|
||||
|
||||
## Access from a Browser
|
||||
|
||||
Once the desktop client is running, it listens on port `9876` locally, and its backend is exactly the same Web console. So while the app is open you can also just point your browser at `http://localhost:9876` for the same full experience as the client UI.
|
||||
|
||||
## Local Data Storage
|
||||
|
||||
All data of the desktop client is stored on your machine:
|
||||
|
||||
- **Config directory**: `~/.cow` in your home folder, holding `config.json` (model keys, channels, etc.) along with logs, cache and other runtime data.
|
||||
- **Workspace**: `~/cow` by default, holding chat history, knowledge base, memory, skills, scheduled tasks and other files produced by the Agent.
|
||||
|
||||
Uninstalling the client does not delete these two directories, so your data is preserved across reinstalls. To fully clean up or migrate to another device, just back up or remove the corresponding folders manually.
|
||||
|
||||
@@ -59,3 +59,9 @@ sudo docker compose up -d
|
||||
<Tip>
|
||||
Back up `config.json` before upgrading. For Docker deployments, mount the workspace directory as a volume to persist data across upgrades.
|
||||
</Tip>
|
||||
|
||||
## Desktop client upgrade
|
||||
|
||||
The [desktop client](/guide/desktop) has built-in auto-update: it checks for new versions automatically and prompts you, so you can download and restart to upgrade in one click.
|
||||
|
||||
You can also grab the latest version anytime from the [download page](https://cowagent.ai/download/).
|
||||
|
||||
@@ -5,6 +5,8 @@ description: CowAgent デスクトップクライアント(macOS / Windows)
|
||||
|
||||
CowAgent は、Agent の実行環境を内蔵したすぐに使えるデスクトップクライアントを提供しています。**Python や依存関係を手動でインストールする必要はありません**。ダウンロードしてインストールするだけで、ローカルでスーパー AI アシスタントを実行できます。
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/desktop-chat-demo-en.png" alt="CowAgent デスクトップクライアント" />
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
<Card title="ダウンロードページへ" icon="download" href="https://cowagent.ai/download/">
|
||||
@@ -34,3 +36,16 @@ CowAgent は、Agent の実行環境を内蔵したすぐに使えるデスク
|
||||
|
||||
- **デスクトップクライアント**:自分の PC での個人利用に最適。すぐに使え、GUI 操作で自動アップデート対応。
|
||||
- **コマンドラインデプロイ**:開発者やサーバーでの長期運用に最適で、カスタマイズ性が高い。詳しくは [クイックスタート](/ja/guide/quick-start) を参照。
|
||||
|
||||
## ブラウザからのアクセス
|
||||
|
||||
デスクトップクライアントは起動するとローカルでポート `9876` をリッスンし、そのバックエンドは Web コンソールとまったく同じです。そのため、アプリを開いている間はブラウザで `http://localhost:9876` にアクセスすれば、クライアント UI と同じ完全な体験が得られます。
|
||||
|
||||
## ローカルデータの保存
|
||||
|
||||
デスクトップクライアントのすべてのデータはお使いのマシンに保存されます:
|
||||
|
||||
- **設定ディレクトリ**:ホームフォルダの `~/.cow`。`config.json`(モデルキーやチャネルなどの設定)のほか、ログ・キャッシュなどの実行データが含まれます。
|
||||
- **ワークスペース**:デフォルトは `~/cow`。会話履歴・ナレッジベース・記憶・スキル・定期タスクなど、Agent が生成したファイルが保存されます。
|
||||
|
||||
クライアントをアンインストールしてもこの 2 つのディレクトリは自動削除されないため、再インストール後もデータは保持されます。完全に削除したい場合や別のデバイスへ移行する場合は、該当するフォルダを手動でバックアップまたは削除してください。
|
||||
|
||||
@@ -59,3 +59,9 @@ sudo docker compose up -d
|
||||
<Tip>
|
||||
アップグレード前に `config.json` 設定ファイルのバックアップを推奨します。Docker 環境でデータを保持する場合は、volume マウントでワークスペースディレクトリを永続化できます。
|
||||
</Tip>
|
||||
|
||||
## デスクトップクライアントのアップグレード
|
||||
|
||||
[デスクトップクライアント](/ja/guide/desktop)は自動アップデート機能を内蔵しており、新しいバージョンを自動的に確認して通知します。ワンクリックでダウンロードして再起動し、アップグレードを完了できます。
|
||||
|
||||
最新バージョンは [ダウンロードページ](https://cowagent.ai/download/) からいつでも手動で入手することもできます。
|
||||
|
||||
@@ -52,15 +52,15 @@ Web コンソール、ログ、ドキュメントが **繁体字中国語(zh-H
|
||||
## 🔒 セキュリティ強化
|
||||
|
||||
- **機密ファイル読み取り防護**:認証情報などの機密ファイルへのアクセスを強化し、迂回による読み取りを防止します。Thanks @fengyl07 (#2913)
|
||||
- **ブラウザアクセス防護**:ブラウザによる内部ネットワークやクラウドサーバーの内部エンドポイントへのリクエストをブロックし、内部サービスへ誘導されるリスクを低減します。Thanks @christop
|
||||
- **ブラウザアクセス防護**:ブラウザによる内部ネットワークやクラウドサーバーの内部エンドポイントへのリクエストをブロックし、内部サービスへ誘導されるリスクを低減します。Thanks @Jiangrong-W
|
||||
- **設定解析の安全化**:設定内容をより安全な方法で解析し、潜在的なコード実行リスクを回避します。Thanks @shunfeng8421
|
||||
|
||||
## 🛠 改善と修正
|
||||
|
||||
- **カスタムプロバイダー対応**:埋め込みモデルとビジョンモデルでカスタムプロバイダーを利用可能に。あわせて Windows でのメモリ取得の問題を修正しました。Thanks @HnBigVolibear
|
||||
- **ファイル編集の安定性向上**:元のインデントをより適切に保持し、あいまい一致の際に無関係な内容を変更しないようにしました。Thanks @xiaweiwei67-stack (#2942)
|
||||
- **コマンド出力の文字化け修正**:コマンドが大量の出力を生成した際に発生し得る中国語の文字化けを修正しました。Thanks @xiaweiwei67-stack (#2941)
|
||||
- **Azure OpenAI の修正**:Azure OpenAI のストリーミング出力および関連する設定の問題を修正しました。Thanks @Eric L
|
||||
- **ファイル編集の安定性向上**:元のインデントをより適切に保持し、あいまい一致の際に無関係な内容を変更しないようにしました。Thanks @weijun-xia (#2942)
|
||||
- **コマンド出力の文字化け修正**:コマンドが大量の出力を生成した際に発生し得る中国語の文字化けを修正しました。Thanks @weijun-xia (#2941)
|
||||
- **Azure OpenAI の修正**:Azure OpenAI のストリーミング出力および関連する設定の問題を修正しました。Thanks @Tunnello
|
||||
- **企業向け WeChat スマートボット**:webhook(コールバック)モードの接続ドキュメントを追加しました。Thanks @6vision
|
||||
- **ディープドリームの切り替え**:`deep_dream_enabled` の専用スイッチを追加し、ディープドリームの蒸留を個別に有効・無効化できます。
|
||||
- **安定性**:Web サービスの接続回収を改善し、自己進化に関するいくつかの問題を修正しました (#2924, #2904)
|
||||
|
||||
@@ -37,6 +37,7 @@ MCP コミュニティ標準に完全準拠しており、Claude Desktop / Curso
|
||||
| `url` | SSE / Streamable HTTP | リモートエンドポイントの URL(`command` と二者択一) |
|
||||
| `type` | リモート | リモートトランスポート種別:`sse` または `streamable-http`(既定は `sse`) |
|
||||
| `headers` | 任意 | リモートリクエストの追加 HTTP ヘッダ(`Authorization` など)。Streamable HTTP のみ |
|
||||
| `scope` | 任意 | OAuth スコープ。OAuth 認可が必要なリモート server のみ使用(任意) |
|
||||
| `disabled` | 任意 | `true` のとき該当サーバーをスキップ。一時的に無効化したいときに便利 |
|
||||
|
||||
### 完全な例
|
||||
@@ -79,6 +80,27 @@ Agent は次のように動作します:
|
||||
1. 既存の MCP 設定ファイルを読み込み、新しい server エントリをマージ(既存の項目は保持)
|
||||
2. 増分の MCP Server を自動でリロードし、次のメッセージから対応する Tool が利用可能に
|
||||
|
||||
## Web 認可(OAuth)
|
||||
|
||||
一部のリモート MCP は OAuth の Web 認可が必要で、そのまま設定すると `401` が返ります。CowAgent は標準的な OAuth フローを内蔵しているため、**token を手動で入力する必要はなく**、通常どおり設定するだけです。例:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"xmind": {
|
||||
"type": "streamable-http",
|
||||
"url": "https://app.xmind.com/api/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
server の初回ロードで `401` が返ると、認可が自動的に開始されます。ローカル実行では**自動的にブラウザが開き**、サーバー環境では**認可リンクがログに出力**されるので、ブラウザで開いてください。承認すると server はすぐにオンラインになり、token は期限切れ時に自動更新されるため、再認可は不要です。
|
||||
|
||||
- **Web サービスが必要**:認可コールバックは Web コンソール(既定ポート `9899`)で受け取るため、Web channel が起動している必要があります。
|
||||
- **認証情報の保存**:token は `~/.cow/mcp_oauth.json` に永続化され、再起動後も再利用されます。
|
||||
- **コールバック URL**:既定は `http://127.0.0.1:9899/mcp/oauth/callback`。サーバーに配置し認可用ブラウザが別の端末にある場合は、`config.json` に `mcp_oauth_redirect_base`(例:`http://あなたのIP:9899`)を設定してください。
|
||||
|
||||
## 動作の仕組み
|
||||
|
||||
- **起動時の非同期ロード**:`mcp.json` に設定された全 server はバックグラウンドで非同期に読み込まれ、メインループをブロックしません。会話はすぐに開始できます
|
||||
|
||||
@@ -22,6 +22,7 @@ Highlights:
|
||||
- **Auto update**: automatic version checks and one-click updates, with download speed optimized across regions
|
||||
- **Native experience**: first-run onboarding, follows the system language, and platform-adaptive window interactions
|
||||
|
||||
Docs: [Desktop Client](https://docs.cowagent.ai/guide/desktop)
|
||||
|
||||
## 📚 Knowledge Base
|
||||
|
||||
@@ -53,15 +54,15 @@ Docs: [Models](https://docs.cowagent.ai/models)
|
||||
## 🔒 Security Hardening
|
||||
|
||||
- **Sensitive file read protection**: hardened access to credential and other sensitive files to prevent bypass reads. Thanks @fengyl07 (#2913)
|
||||
- **Browser access protection**: blocks browser requests targeting internal network and cloud server internal endpoints, reducing the risk of being tricked into reaching internal services. Thanks @christop
|
||||
- **Browser access protection**: blocks browser requests targeting internal network and cloud server internal endpoints, reducing the risk of being tricked into reaching internal services. Thanks @Jiangrong-W
|
||||
- **Safer config parsing**: config content is parsed in a safer way to avoid potential code execution risks. Thanks @shunfeng8421
|
||||
|
||||
## 🛠 Improvements & Fixes
|
||||
|
||||
- **Custom provider support**: embedding and vision models can now use custom providers; also fixed a memory query issue on Windows. Thanks @HnBigVolibear
|
||||
- **More reliable file editing**: better preserves original indentation, and fuzzy matching no longer touches unrelated content. Thanks @xiaweiwei67-stack (#2942)
|
||||
- **Command output encoding fix**: fixed garbled Chinese characters when a command produces large output. Thanks @xiaweiwei67-stack (#2941)
|
||||
- **Azure OpenAI fixes**: fixed streaming output and related configuration issues for Azure OpenAI. Thanks @Eric L
|
||||
- **More reliable file editing**: better preserves original indentation, and fuzzy matching no longer touches unrelated content. Thanks @weijun-xia (#2942)
|
||||
- **Command output encoding fix**: fixed garbled Chinese characters when a command produces large output. Thanks @weijun-xia (#2941)
|
||||
- **Azure OpenAI fixes**: fixed streaming output and related configuration issues for Azure OpenAI. Thanks @Tunnello
|
||||
- **WeCom Smart Bot**: added channel docs for the webhook (callback) mode. Thanks @6vision
|
||||
- **Deep Dream toggle**: added a dedicated `deep_dream_enabled` switch to enable or disable Deep Dream distillation independently.
|
||||
- **Stability**: improved connection recycling in the Web service and fixed several Self-Evolution issues (#2924, #2904)
|
||||
|
||||
@@ -37,6 +37,7 @@ Fully compatible with the MCP community standard, identical to Claude Desktop /
|
||||
| `url` | SSE / Streamable HTTP | Remote endpoint URL (alternative to `command`) |
|
||||
| `type` | Remote | Remote transport type: `sse` or `streamable-http` (defaults to `sse`) |
|
||||
| `headers` | No | Extra HTTP headers for remote requests (e.g. `Authorization`); Streamable HTTP only |
|
||||
| `scope` | No | OAuth scope, only for remote servers that require OAuth authorization (optional) |
|
||||
| `disabled` | No | When `true`, this server is skipped — handy for temporary disabling |
|
||||
|
||||
### Full Example
|
||||
@@ -79,6 +80,27 @@ The Agent will:
|
||||
1. Read the existing MCP config and merge the new server entry, preserving existing ones
|
||||
2. Hot-reload the new MCP server, so the corresponding tools become available on the next message
|
||||
|
||||
## Web Authorization (OAuth)
|
||||
|
||||
Some remote MCP servers require OAuth web authorization, and connecting to them directly returns `401`. CowAgent has a built-in standard OAuth flow, so **no manual token is needed** — just configure the server normally, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"xmind": {
|
||||
"type": "streamable-http",
|
||||
"url": "https://app.xmind.com/api/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When a server returns `401` on its first load, authorization starts automatically: running locally **opens the browser automatically**, while server deployments **print the authorization link to the log** for you to open in a browser. Once you approve, the server comes online immediately; tokens are refreshed automatically on expiry, so you never have to re-authorize.
|
||||
|
||||
- **Requires the web service**: The authorization callback is received by the web console (default port `9899`), so the Web channel must be running.
|
||||
- **Credential storage**: Tokens are persisted in `~/.cow/mcp_oauth.json` and reused across restarts.
|
||||
- **Callback URL**: Defaults to `http://127.0.0.1:9899/mcp/oauth/callback`. If deployed on a server with the authorizing browser on another device, set `mcp_oauth_redirect_base` in `config.json` (e.g. `http://YOUR_IP:9899`).
|
||||
|
||||
## How It Works
|
||||
|
||||
- **Async loading at startup**: All servers configured in `mcp.json` are loaded asynchronously in the background, never blocking the main loop — chat is usable immediately.
|
||||
|
||||
@@ -5,6 +5,8 @@ description: 下载并使用 CowAgent 桌面客户端(macOS / Windows)
|
||||
|
||||
CowAgent 提供开箱即用的桌面客户端,内置 Agent 运行环境,**无需手动安装 Python 或依赖**,下载安装后即可在本地运行你的超级 AI 助理。
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/zh/desktop-chat-demo-zh.png" alt="CowAgent 桌面客户端" />
|
||||
|
||||
## 下载安装
|
||||
|
||||
<Card title="前往下载页" icon="download" href="https://cowagent.ai/zh/download/">
|
||||
@@ -25,11 +27,25 @@ CowAgent 提供开箱即用的桌面客户端,内置 Agent 运行环境,**
|
||||
3. 从桌面或开始菜单打开 CowAgent 即可。
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## 自动更新
|
||||
|
||||
桌面客户端内置自动更新能力。有新版本时会自动检测并提示,你也可以在应用左下角菜单中手动「检查更新」,一键下载并重启完成升级。
|
||||
|
||||
## 与命令行部署的区别
|
||||
|
||||
- **桌面客户端**:适合个人在本地电脑使用,开箱即用,图形界面操作,自动更新。
|
||||
- **命令行部署**:适合开发者或服务器长期运行,可定制性更强,详见 [一键安装](/zh/guide/quick-start)。
|
||||
- **桌面客户端**:适合个人用户开箱即用,无需安装任何依赖,图形界面操作,支持自动更新。
|
||||
- **命令行部署**:源码运行方式,适合开发者在本地或服务器部署,方便扩展功能,可定制性更强,详见 [一键安装](/zh/guide/quick-start)。
|
||||
|
||||
## 通过浏览器访问
|
||||
|
||||
桌面客户端启动后会在本机监听 `9876` 端口,其后端与 Web 控制台完全一致。因此在打开客户端的同时,也可以直接用浏览器访问 `http://localhost:9876`,获得与客户端界面一致的完整体验。
|
||||
|
||||
## 本地数据存储
|
||||
|
||||
桌面客户端的所有数据都保存在本机:
|
||||
|
||||
- **配置文件**:位于用户目录下的 `~/.cow`,包含 `config.json`(模型密钥、通道等配置)以及日志、缓存等运行数据。
|
||||
- **工作空间**:默认位于 `~/cow`,用于存放对话记录、知识库、记忆、技能、定时任务等 Agent 产生的文件。
|
||||
|
||||
卸载客户端不会自动删除这两个目录,重装后数据依然保留。如需彻底清理或迁移到其他设备,手动备份或删除对应目录即可。
|
||||
|
||||
@@ -59,3 +59,9 @@ sudo docker compose up -d
|
||||
<Tip>
|
||||
升级前建议备份 `config.json` 配置文件。Docker 环境下如需保留数据,可通过 volume 挂载持久化工作空间目录。
|
||||
</Tip>
|
||||
|
||||
## 客户端升级
|
||||
|
||||
[桌面客户端](/zh/guide/desktop)内置自动更新能力,有新版本时会自动检查并提示,一键即可下载并重启完成升级。
|
||||
|
||||
你也可以随时前往[下载页](https://cowagent.ai/zh/download/)手动下载最新版本安装。
|
||||
|
||||
@@ -22,6 +22,7 @@ description: CowAgent 2.1.3:正式推出桌面客户端(macOS / Windows)
|
||||
- **自动更新**:支持版本自动检查与一键更新,优化不同地区的下载速度
|
||||
- **原生体验**:首次启动引导、跟随系统语言、平台自适应的窗口交互
|
||||
|
||||
相关文档:[桌面客户端](https://docs.cowagent.ai/zh/guide/desktop)
|
||||
|
||||
## 📚 知识库
|
||||
|
||||
@@ -54,15 +55,15 @@ Web 控制台、日志与文档新增 **繁体中文(zh-Hant)** 支持,界
|
||||
## 🔒 安全加固
|
||||
|
||||
- **敏感文件读取防护**:加固对凭证等敏感文件的访问,防止绕过读取。Thanks @fengyl07 (#2913)
|
||||
- **浏览器访问防护**:浏览器访问网页时拦截指向内网及云服务器内部地址的请求,降低被诱导访问内部服务的风险。Thanks @christop
|
||||
- **浏览器访问防护**:浏览器访问网页时拦截指向内网及云服务器内部地址的请求,降低被诱导访问内部服务的风险。Thanks @Jiangrong-W
|
||||
- **配置解析加固**:使用更安全的方式解析配置内容,避免潜在的代码执行风险。Thanks @shunfeng8421
|
||||
|
||||
## 🛠 体验优化与修复
|
||||
|
||||
- **自定义供应商扩展**:嵌入与视觉模型支持配置自定义供应商;同时修复记忆查询在 Windows 下的问题。Thanks @HnBigVolibear
|
||||
- **文件编辑更稳**:编辑文件时更好地保留原有缩进,且模糊匹配时不改动未涉及的内容。Thanks @xiaweiwei67-stack (#2942)
|
||||
- **命令输出乱码修复**:修复执行命令产生大量输出时可能出现的中文乱码。Thanks @xiaweiwei67-stack (#2941)
|
||||
- **Azure OpenAI 修复**:修复 Azure OpenAI 的流式输出与相关配置问题。Thanks @Eric L
|
||||
- **文件编辑更稳**:编辑文件时更好地保留原有缩进,且模糊匹配时不改动未涉及的内容。Thanks @weijun-xia (#2942)
|
||||
- **命令输出乱码修复**:修复执行命令产生大量输出时可能出现的中文乱码。Thanks @weijun-xia (#2941)
|
||||
- **Azure OpenAI 修复**:修复 Azure OpenAI 的流式输出与相关配置问题。Thanks @Tunnello
|
||||
- **企业微信智能机器人**:补充 webhook(回调)模式的接入文档。Thanks @6vision
|
||||
- **深度梦境开关**:新增 `deep_dream_enabled` 配置开关,可按需开启或关闭深度梦境。
|
||||
- **稳定性提升**:优化 Web 服务的连接回收,并修复自主进化过程中的若干问题 (#2924, #2904)
|
||||
|
||||
@@ -37,6 +37,7 @@ Docker 部署时,官方 `docker-compose.yml` 已经把宿主机 `./cow` 挂载
|
||||
| `url` | SSE / Streamable HTTP | 远程端点 URL(与 `command` 二选一) |
|
||||
| `type` | 远程 | 远程传输类型,可选 `sse` 或 `streamable-http`,默认 `sse` |
|
||||
| `headers` | 否 | 远程请求附加 HTTP 头(如 `Authorization`),仅 Streamable HTTP 使用 |
|
||||
| `scope` | 否 | OAuth 授权范围,仅需要 OAuth 授权的远程 server 使用(可选) |
|
||||
| `disabled` | 否 | `true` 时跳过该 server,便于临时关闭 |
|
||||
|
||||
### 完整示例
|
||||
@@ -79,6 +80,27 @@ Agent 会:
|
||||
1. 访问 MCP 配置文件,合并新 server 配置,保留已有项
|
||||
2. 自动重载增量的 MCP Server,下一次对话即可使用相应 Tools
|
||||
|
||||
## 网页授权(OAuth)
|
||||
|
||||
部分远程 MCP需要 OAuth 网页授权,直接配置会返回 `401`。CowAgent 内置标准 OAuth 流程,**无需手填 token**,正常配置即可,例如:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"xmind": {
|
||||
"type": "streamable-http",
|
||||
"url": "https://app.xmind.com/api/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
server 首次加载遇到 `401` 时会自动发起授权:本机运行会**自动打开浏览器**,服务器部署则把**授权链接打印到日志**,复制到浏览器打开。授权同意后即完成,该 server 随即上线,令牌过期自动刷新,无需重复授权。
|
||||
|
||||
- **依赖 Web 服务**:授权回调由 Web 控制台(默认端口 `9899`)接收,需保证 Web channel 正在运行。
|
||||
- **凭证存储**:令牌持久化在 `~/.cow/mcp_oauth.json`,重启后复用。
|
||||
- **回调地址**:默认 `http://127.0.0.1:9899/mcp/oauth/callback`;若部署在服务器、授权浏览器在另一台设备,在 `config.json` 设置 `mcp_oauth_redirect_base`(如 `http://你的IP:9899`)即可。
|
||||
|
||||
## 工作方式
|
||||
|
||||
- 启动时**异步加载**:`mcp.json` 中配置的所有 server 会在后台异步加载,不阻塞主流程,对话可以立刻使用
|
||||
|
||||
@@ -98,6 +98,41 @@ class TestEditFuzzyPreservesWhitespace(unittest.TestCase):
|
||||
"def foo():\n x = 100\n y = 2\n return x + y\n",
|
||||
)
|
||||
|
||||
def test_exact_match_rejects_multiple_occurrences(self):
|
||||
# Two byte-identical statements; the exact-match path applies and the
|
||||
# uniqueness guard counts exact occurrences, so the ambiguous edit is
|
||||
# rejected instead of silently editing only the first.
|
||||
with open(self.path, "w", encoding="utf-8") as f:
|
||||
f.write("a = 1\nb = 2\na = 1\n")
|
||||
result = self.tool.execute({
|
||||
"path": self.path,
|
||||
"oldText": "a = 1",
|
||||
"newText": "a = 9",
|
||||
})
|
||||
self.assertEqual(result.status, "error", result.result)
|
||||
self.assertIn("occurrences", result.result)
|
||||
# An ambiguous match must leave the file untouched.
|
||||
self.assertEqual(self._read(), "a = 1\nb = 2\na = 1\n")
|
||||
|
||||
def test_fuzzy_match_rejects_multiple_occurrences(self):
|
||||
# oldText uses loose spacing, so the exact match fails and the fuzzy
|
||||
# path runs. The uniqueness guard now counts with the SAME regex used
|
||||
# to match/replace, so an ambiguous fuzzy match (two hits) is rejected
|
||||
# rather than silently editing the first one.
|
||||
with open(self.path, "w", encoding="utf-8") as f:
|
||||
f.write("def foo():\n x = 1\n y = 2\n x = 1\n")
|
||||
result = self.tool.execute({
|
||||
"path": self.path,
|
||||
"oldText": "x = 1",
|
||||
"newText": "x = 99",
|
||||
})
|
||||
self.assertEqual(result.status, "error", result.result)
|
||||
self.assertIn("occurrences", result.result)
|
||||
self.assertEqual(
|
||||
self._read(),
|
||||
"def foo():\n x = 1\n y = 2\n x = 1\n",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user