Skip to content

Build and run agents you can see, understand and trust.

feat(hub): support to install MCP and skills from MCP/skill hubs (#2197)

DavdGao81d68a07656a
diff --git a/README.md b/README.md
index 4415c1ced..f152653b3 100644
--- a/README.md
+++ b/README.md
@@ -73,6 +73,8 @@ rather than constraining them with strict prompts and opinionated orchestrations
## News
<!-- BEGIN NEWS -->
+- **[2026-08] `INTE`:** GitHub MCP Registry and ClawHub supported as built-in hubs. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
+- **[2026-08] `FEAT`:** MCP & Skill Hub supported — browse a hub, install into your library, add to a workspace. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
- **[2026-07] `INTE`:** Daytona-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `INTE`:** K8s, OpenSandbox-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `INTE`:** ReMe long-term memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
@@ -81,7 +83,6 @@ rather than constraining them with strict prompts and opinionated orchestrations
- **[2026-06] `FEAT`:** RAG supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `INTE`:** Mem0 supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/en)
- **[2026-06] `FEAT`:** Agent Team supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
-- **[2026-05] `RELS`:** AgentScope 2.0 released! [Docs](https://docs.agentscope.io/)
<!-- END NEWS -->
[More news →](./docs/NEWS.md)
diff --git a/README_zh.md b/README_zh.md
index 5d732f1c3..9e7e25f67 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -73,6 +73,8 @@ AgentScope 2.0 是一款面向生产、易于使用的智能体框架,提供
## 新闻
<!-- BEGIN NEWS -->
+- **[2026-08] `集成`:** 内置集成 GitHub MCP Registry 与 ClawHub。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
+- **[2026-08] `功能`:** 支持 MCP & Skill Hub —— 浏览 hub、安装到个人库、再添加到工作区。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
- **[2026-07] `集成`:** 集成 Daytona 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `集成`:** 集成 K8s,OpenSandbox 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `集成`:** 集成 ReMe 长期记忆。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
@@ -81,7 +83,6 @@ AgentScope 2.0 是一款面向生产、易于使用的智能体框架,提供
- **[2026-06] `功能`:** 支持多模态 RAG。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [文档](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `集成`:** 集成 Mem0 长期记忆。 [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/zh)
- **[2026-06] `功能`:** 支持 Agent Team。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/agent-team)
-- **[2026-05] `发布`:** AgentScope 2.0 已发布![文档](https://docs.agentscope.io/)
<!-- END NEWS -->
[更多新闻 →](./docs/NEWS_zh.md)
diff --git a/docs/NEWS.md b/docs/NEWS.md
index 6798954f9..a6475fb3a 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,6 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-08] `INTE`:** GitHub MCP Registry and ClawHub supported as built-in hubs. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
+- **[2026-08] `FEAT`:** MCP & Skill Hub supported — browse a hub, install into your library, add to a workspace. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
- **[2026-07] `INTE`:** Daytona-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `INTE`:** K8s, OpenSandbox-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `INTE`:** ReMe long-term memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index 90e0f3c2c..80f420330 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,6 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-08] `集成`:** 内置集成 GitHub MCP Registry 与 ClawHub。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
+- **[2026-08] `功能`:** 支持 MCP & Skill Hub —— 浏览 hub、安装到个人库、再添加到工作区。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
- **[2026-07] `集成`:** 集成 Daytona 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `集成`:** 集成 K8s,OpenSandbox 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `集成`:** 集成 ReMe 长期记忆。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
diff --git a/examples/agent_service/main.py b/examples/agent_service/main.py
index 5b91325e9..9e83b9ab7 100644
--- a/examples/agent_service/main.py
+++ b/examples/agent_service/main.py
@@ -7,6 +7,7 @@ from fastapi.middleware import Middleware
from fastapi.middleware.cors import CORSMiddleware
from agentscope.app import create_app, SubAgentTemplate
+from agentscope.app.hub import ClawSkillHub, GitHubMCPHub
from agentscope.app.message_bus import InMemoryMessageBus
from agentscope.app.rag.knowledge_base_manager import CollectionPerKbManager
from agentscope.app.storage import RedisStorage
@@ -72,6 +73,12 @@ app = create_app(
storage=storage,
vector_store=vector_store,
),
+ # Resource hubs the UI browses under /hub. Neither needs credentials
+ # of its own — an individual MCP card declares whatever key it wants
+ # from the user in its ``inputs_schema``. Passing a ClawHub token
+ # only raises the rate limit.
+ mcp_hubs=[GitHubMCPHub()],
+ skill_hubs=[ClawSkillHub(api_token=os.getenv("CLAWHUB_API_TOKEN"))],
# Customize your own subagent templates
custom_subagent_templates=[
SubAgentTemplate(
diff --git a/examples/web_ui/frontend/src/App.tsx b/examples/web_ui/frontend/src/App.tsx
index 9584518e1..b7d583d4d 100644
--- a/examples/web_ui/frontend/src/App.tsx
+++ b/examples/web_ui/frontend/src/App.tsx
@@ -3,6 +3,8 @@ import { useMemo, useState } from 'react';
import { createBrowserRouter, Navigate, RouterProvider, useNavigate } from 'react-router-dom';
import { Toaster } from 'sonner';
+import { MCPHubPage } from './pages/mcp';
+import { SkillHubPage } from './pages/skill';
import { RouteError } from '@/components/error/RouteError';
import { AppLayout } from '@/components/layout/AppLayout';
import { buildChatTour } from '@/components/tour/chatTourSteps';
@@ -46,6 +48,10 @@ const router = createBrowserRouter([
},
{ path: '/schedule', element: <SchedulePage /> },
{ path: '/credential', element: <CredentialPage /> },
+ { path: '/mcp', element: <MCPHubPage /> },
+ { path: '/mcp/:hubId', element: <MCPHubPage /> },
+ { path: '/skill', element: <SkillHubPage /> },
+ { path: '/skill/:hubId', element: <SkillHubPage /> },
{ path: '/knowledge', element: <KnowledgePage /> },
{ path: '/knowledge/:kbId', element: <KnowledgePage /> },
],
diff --git a/examples/web_ui/frontend/src/api/hub.ts b/examples/web_ui/frontend/src/api/hub.ts
new file mode 100644
index 000000000..2b63a2c46
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/hub.ts
@@ -0,0 +1,89 @@
+import { client } from './client';
+import type {
+ HubBrowseParams,
+ HubInfo,
+ InstallMCPRequest,
+ MCPCard,
+ MCPHubPage,
+ MCPView,
+ SkillCard,
+ SkillHubPage,
+ SkillView,
+} from './types';
+
+/**
+ * Card ids are opaque and may contain characters that are not path-safe —
+ * ClawHub's search endpoint, for one, returns ids containing `:`.
+ */
+const segment = (value: string) => encodeURIComponent(value);
+
+/** Drop empty filters so the backend applies its own defaults. */
+function browseQuery(params?: HubBrowseParams): Record<string, string> {
+ const query: Record<string, string> = {};
+ if (params?.q) query.q = params.q;
+ if (params?.cursor) query.cursor = params.cursor;
+ if (params?.limit !== undefined) query.limit = String(params.limit);
+ return query;
+}
+
+/**
+ * Resource hubs. Browsing is three levels deep — pick a hub, browse its
+ * cards, install one. Cards are never merged across hubs, so each hub
+ * paginates on its own.
+ */
+export const hubApi = {
+ mcp: {
+ listHubs: () => client.get<HubInfo[]>('/hub/mcp'),
+
+ listCards: (hubId: string, params?: HubBrowseParams) =>
+ client.get<MCPHubPage>(`/hub/mcp/${segment(hubId)}/cards`, browseQuery(params)),
+
+ getCard: (hubId: string, cardId: string) =>
+ client.get<MCPCard>(`/hub/mcp/${segment(hubId)}/cards/${segment(cardId)}`),
+
+ /**
+ * Renders the card's template with `body.values` into the user's
+ * library. No workspace is involved — putting the MCP into a session
+ * is a separate act. The config is not connection-tested, so a wrong
+ * API key surfaces on first use, not here. A 409 means the name is
+ * taken — retry with `body.name` set.
+ */
+ install: (
+ hubId: string,
+ cardId: string,
+ body: InstallMCPRequest,
+ options?: { silent?: boolean },
+ ) =>
+ client.post<MCPView>(
+ `/hub/mcp/${segment(hubId)}/cards/${segment(cardId)}/install`,
+ body,
+ undefined,
+ options,
+ ),
+ },
+
+ skill: {
+ listHubs: () => client.get<HubInfo[]>('/hub/skill'),
+
+ listCards: (hubId: string, params?: HubBrowseParams) =>
+ client.get<SkillHubPage>(`/hub/skill/${segment(hubId)}/cards`, browseQuery(params)),
+
+ /** Unlike the list endpoint, this also fetches the `SKILL.md` body. */
+ getCard: (hubId: string, cardId: string) =>
+ client.get<SkillCard>(`/hub/skill/${segment(hubId)}/cards/${segment(cardId)}`),
+
+ /**
+ * Records the card in the user's library. Like the MCP install this
+ * touches no workspace, and it does not download the archive — that
+ * happens when the skill is put into a workspace. A 409 means the
+ * name is taken; retry with `name` set.
+ */
+ install: (hubId: string, cardId: string, name?: string, options?: { silent?: boolean }) =>
+ client.post<SkillView>(
+ `/hub/skill/${segment(hubId)}/cards/${segment(cardId)}/install`,
+ undefined,
+ name ? { name } : undefined,
+ options,
+ ),
+ },
+};
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 4a8abdcf7..c10993a01 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -4,6 +4,9 @@ export { sessionApi } from './session';
export { credentialApi } from './credential';
export { chatApi } from './chat';
export { workspaceApi } from './workspace';
+export { hubApi } from './hub';
+export { mcpApi } from './mcp';
+export { skillApi } from './skill';
export { scheduleApi } from './schedule';
export { modelApi, ttsModelApi } from './model';
export { knowledgeBaseApi } from './knowledgeBase';
diff --git a/examples/web_ui/frontend/src/api/mcp.ts b/examples/web_ui/frontend/src/api/mcp.ts
new file mode 100644
index 000000000..6729f3ff1
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/mcp.ts
@@ -0,0 +1,25 @@
+import { client } from './client';
+import type { MCPView, UpdateMCPRequest } from './types';
+
+/**
+ * The user's own library of installed MCPs, which is where a hub install
+ * lands. Separate from `workspaceApi`, which manages what one session's
+ * workspace actually holds.
+ */
+export const mcpApi = {
+ list: () => client.get<MCPView[]>('/mcp'),
+
+ /**
+ * Renames, enables/disables, or re-keys it. Changing `values` is a
+ * re-render from the hub card, so the originating hub must still be
+ * registered and reachable.
+ */
+ update: (mcpId: string, body: UpdateMCPRequest) =>
+ client.patch<MCPView>(`/mcp/${encodeURIComponent(mcpId)}`, body),
+
+ /**
+ * Removes it from the library. Workspaces that already hold this MCP keep
+ * it — the relation is derived by name, not a foreign key.
+ */
+ remove: (mcpId: string) => client.delete(`/mcp/${encodeURIComponent(mcpId)}`),
+};
diff --git a/examples/web_ui/frontend/src/api/skill.ts b/examples/web_ui/frontend/src/api/skill.ts
new file mode 100644
index 000000000..913203472
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/skill.ts
@@ -0,0 +1,21 @@
+import { client } from './client';
+import type { SkillRecord, SkillView } from './types';
+
+/**
+ * The user's own library of installed skills, which is where a hub install
+ * lands. Separate from `workspaceApi.skill`, which manages the skills one
+ * session's workspace actually holds.
+ */
+export const skillApi = {
+ list: () => client.get<SkillView[]>('/skill'),
+
+ /** Unlike the list endpoint, this also carries the `SKILL.md` body. */
+ get: (skillId: string) => client.get<SkillRecord>(`/skill/${encodeURIComponent(skillId)}`),
+
+ /**
+ * Removes it from the library. Workspaces that already hold this skill
+ * keep their copy — the files were extracted into the workspace, and this
+ * record was only where they came from.
+ */
+ remove: (skillId: string) => client.delete(`/skill/${encodeURIComponent(skillId)}`),
+};
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 344691043..95917ee63 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -389,6 +389,12 @@ export interface ToolInfo {
export interface MCPClientStatus extends MCPClient {
is_healthy: boolean;
tools: ToolInfo[];
+ /**
+ * Why listing this MCP's tools failed. `null` when healthy — a red dot
+ * alone leaves nothing to act on, since a wrong API key, an unreachable
+ * host and a missing command all look the same.
+ */
+ error: string | null;
}
// ─── Skill ────────────────────────────────────────────────────────────────────
@@ -401,10 +407,214 @@ export interface Skill {
updated_at: number;
}
+/**
+ * @deprecated The path is resolved on the server, which only means
+ * anything for a single-host deployment. Upload a folder or install
+ * from the library instead.
+ */
export interface AddSkillRequest {
skill_path: string;
}
+// ─── Hub ──────────────────────────────────────────────────────────────────────
+
+/** One registered hub, as shown in the hub picker. */
+export interface HubInfo {
+ hub_id: string;
+ display_name: string;
+ description: string;
+ /** `null` when the hub has no icon; fall back rather than leave a gap. */
+ icon_url: string | null;
+}
+
+/**
+ * Query for browsing one hub. Pagination is cursor-based — pass the previous
+ * page's `next_cursor` to load more; a `null` cursor means the end.
+ */
+export interface HubBrowseParams {
+ /** Keyword search. Some hubs answer this from a separate, unpaginated endpoint. */
+ q?: string;
+ cursor?: string;
+ /** 1-200, defaults to 20 server-side. */
+ limit?: number;
+}
+
+interface HubCardBase {
+ /** The hub this card came from. Together with `id` it addresses the card globally. */
+ hub_id: string;
+ /**
+ * The card's id on its hub — opaque, and not necessarily URL-safe (some
+ * registries use ids containing `:`). Always encode it into a path.
+ */
+ id: string;
+ name: string;
+ display_name?: string | null;
+ description: string;
+ tags: string[];
+ version?: string | null;
+}
+
+/**
+ * An MCP listing: a *template*, not something connectable. `config_template`
+ * holds `${...}` placeholders that the server fills from the values submitted
+ * at install time — never substitute them client-side.
+ */
+export interface MCPCard extends HubCardBase {
+ is_stateful: boolean;
+ updated_at?: number | null;
+ /** Who published it. `null` when the hub does not say. */
+ author?: string | null;
+ /** An image representing it. `null` when the hub offers none. */
+ icon_url?: string | null;
+ /** Its page on the hub's website. `null` if it has none. */
+ url?: string | null;
+ /** `null` means uncounted, which is not the same as zero. */
+ installs?: number | null;
+ downloads?: number | null;
+ /** `none` — install directly, no form. `inputs` — render `inputs_schema`. */
+ auth: 'none' | 'inputs';
+ /**
+ * JSON Schema for the install form. Empty (no `properties`) when the card
+ * needs no configuration, so branch on `auth` before rendering.
+ * Secret fields carry `writeOnly: true` / `format: 'password'`.
+ */
+ inputs_schema: Partial<JSONSchema>;
+ /**
+ * The server's long-form docs. Only populated by the detail endpoint —
+ * READMEs run to tens of kilobytes, so listings leave them out.
+ */
+ readme?: string | null;
+ /** Shown read-only; the placeholders are resolved server-side. */
+ config_template: StdioMCPConfig | HttpMCPConfig;
+}
+
+/** A skill listing. Unlike an MCP there is nothing to configure. */
+export interface SkillCard extends HubCardBase {
+ updated_at?: number | null;
+ /** Who published it. `null` when the hub does not say. */
+ author?: string | null;
+ /**
+ * An image representing the skill. `null` when the hub offers none —
+ * fall back rather than rendering a broken image.
+ */
+ icon_url?: string | null;
+ /**
+ * How many times the skill has been installed. `null` means the hub does
+ * not count installs — which is not the same as zero, so don't render it.
+ */
+ installs?: number | null;
+ /** How many times it has been downloaded. `null` when uncounted. */
+ downloads?: number | null;
+ /** The skill's page on the hub's website. `null` if it has none. */
+ url?: string | null;
+ /** The `SKILL.md` body — only populated by the detail endpoint. */
+ markdown?: string | null;
+ metadata: Record<string, unknown>;
+}
+
+export interface MCPHubPage {
+ cards: MCPCard[];
+ /** `null` when this is the last page. */
+ next_cursor: string | null;
+}
+
+export interface SkillHubPage {
+ cards: SkillCard[];
+ next_cursor: string | null;
+}
+
+/**
+ * The outcome of putting library MCPs into a workspace, reported per MCP:
+ * connecting happens one at a time, so a bad API key on the third pick must
+ * not throw away the two that worked.
+ */
+export interface AddFromLibraryResponse {
+ /** Now in the workspace. Excludes ones already present. */
+ added: string[];
+ /** Whatever could not be added, mapped to why. */
+ failed: Record<string, string>;
+}
+
+/** A library edit. Omitted fields are left alone. */
+export interface UpdateMCPRequest {
+ name?: string;
+ /**
+ * New answers, merged over the stored ones — send only what changed, so
+ * a write-only field the form never echoed back survives.
+ */
+ values?: Record<string, unknown>;
+ enabled?: boolean;
+}
+
+export interface InstallMCPRequest {
+ /**
+ * Name to install under, defaulting to the card's. Must match
+ * `[a-zA-Z0-9_-]+`; use it to resolve a 409 name clash.
+ */
+ name?: string | null;
+ /** Answers to `inputs_schema`, e.g. API keys. */
+ values: Record<string, unknown>;
+}
+
+// ─── Installed MCPs and skills ────────────────────────────────────────────────
+
+/**
+ * One MCP in the user's own library, which is where an install lands —
+ * distinct from `WorkspaceMCP`, which is what one session's workspace holds.
+ *
+ * The rendered config is not exposed: it carries the values submitted at
+ * install time, API keys included.
+ */
+export interface MCPView {
+ id: string;
+ /** Unique per user — the handle a workspace refers to it by. */
+ name: string;
+ is_stateful: boolean;
+ enabled: boolean;
+ /**
+ * Snapshotted from the card at install time, so they survive the hub
+ * going away — and may lag behind it.
+ */
+ display_name: string | null;
+ description: string;
+ tags: string[];
+ author: string | null;
+ icon_url: string | null;
+ url: string | null;
+ /** `null` when the MCP was added by hand rather than from a hub. */
+ hub_id: string | null;
+ card_id: string | null;
+ version: string | null;
+}
+
+/**
+ * One skill in the user's own library. Unlike an MCP, the skill's files are
+ * not stored — the record says where they came from, and the archive is
+ * re-fetched from the hub when the skill reaches a workspace.
+ */
+export interface SkillView {
+ id: string;
+ /** Unique per user — the handle a workspace refers to it by. */
+ name: string;
+ enabled: boolean;
+ display_name: string | null;
+ description: string;
+ tags: string[];
+ /** Snapshotted from the card at install time, so the library keeps the
+ * identity of the listing it came from. */
+ author: string | null;
+ icon_url: string | null;
+ url: string | null;
+ hub_id: string | null;
+ card_id: string | null;
+ version: string | null;
+}
+
+/** A library skill with its `SKILL.md` body, from the detail endpoint. */
+export interface SkillRecord extends SkillView {
+ markdown: string;
+}
+
// ─── Schedule ─────────────────────────────────────────────────────────────────
export type PermissionMode =
diff --git a/examples/web_ui/frontend/src/api/workspace.ts b/examples/web_ui/frontend/src/api/workspace.ts
index 2c8e37b9b..cd3a767c9 100644
--- a/examples/web_ui/frontend/src/api/workspace.ts
+++ b/examples/web_ui/frontend/src/api/workspace.ts
@@ -1,5 +1,101 @@
-import { client } from './client';
-import type { AddSkillRequest, MCPClient, MCPClientStatus, Skill } from './types';
+import { ApiError, client, getBaseUrl, getUserId } from './client';
+import type { UploadProgress } from './knowledgeBase';
+import type {
+ AddFromLibraryResponse,
+ AddSkillRequest,
+ MCPClient,
+ MCPClientStatus,
+ Skill,
+} from './types';
+
+export interface UploadOptions {
+ /** Fired with byte-level progress while the body is streamed. */
+ onProgress?: (progress: UploadProgress) => void;
+ /** Aborts the upload; rejects with a `DOMException` named `AbortError`. */
+ signal?: AbortSignal;
+}
+
+/**
+ * XHR-based folder upload — `fetch` surfaces no byte-level send
+ * progress, so anything driving a progress bar has to use XHR.
+ *
+ * The manifest rides alongside the parts because the server builds a
+ * tar as they arrive, and a tar header needs each member's size before
+ * its bytes — which a multipart part does not declare.
+ */
+function uploadSkillXhr(
+ agentId: string,
+ sessionId: string,
+ files: File[],
+ options: UploadOptions = {},
+): Promise<void> {
+ const { onProgress, signal } = options;
+ const formData = new FormData();
+ formData.append(
+ 'manifest',
+ JSON.stringify({
+ entries: files.map((file) => ({
+ path: file.webkitRelativePath || file.name,
+ size: file.size,
+ })),
+ }),
+ );
+ for (const file of files) formData.append('files', file);
+
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(new DOMException('Aborted', 'AbortError'));
+ return;
+ }
+
+ const xhr = new XMLHttpRequest();
+ const url = new URL('/workspace/skill/upload', getBaseUrl());
+ url.searchParams.set('agent_id', agentId);
+ url.searchParams.set('session_id', sessionId);
+ xhr.open('POST', url.toString(), true);
+ xhr.setRequestHeader('X-User-ID', getUserId());
+
+ const onAbort = () => xhr.abort();
+ signal?.addEventListener('abort', onAbort, { once: true });
+ const cleanup = () => signal?.removeEventListener('abort', onAbort);
+
+ if (xhr.upload && onProgress) {
+ xhr.upload.onprogress = (e) => {
+ onProgress({
+ loaded: e.loaded,
+ total: e.lengthComputable ? e.total : 0,
+ });
+ };
+ }
+
+ xhr.onload = () => {
+ cleanup();
+ if (xhr.status >= 200 && xhr.status < 300) {
+ resolve();
+ return;
+ }
+ let detail = xhr.responseText || xhr.statusText;
+ try {
+ const json = JSON.parse(xhr.responseText) as { detail?: unknown };
+ if (typeof json.detail === 'string') detail = json.detail;
+ else if (json.detail !== undefined) detail = JSON.stringify(json.detail);
+ } catch {
+ // keep raw text
+ }
+ reject(new ApiError(xhr.status, detail));
+ };
+ xhr.onerror = () => {
+ cleanup();
+ reject(new ApiError(0, 'Network error'));
+ };
+ xhr.onabort = () => {
+ cleanup();
+ reject(new DOMException('Aborted', 'AbortError'));
+ };
+
+ xhr.send(formData);
+ });
+}
export const workspaceApi = {
mcp: {
@@ -12,6 +108,18 @@ export const workspaceApi = {
add: (agentId: string, sessionId: string, mcp: MCPClient) =>
client.post<void>('/workspace/mcp', mcp, { agent_id: agentId, session_id: sessionId }),
+ /**
+ * Puts MCPs the user has already installed into this workspace.
+ * Ids, not configs — the rendered config never leaves the server,
+ * so the client has no way to reconstruct one.
+ */
+ addFromLibrary: (agentId: string, sessionId: string, mcpIds: string[]) =>
+ client.post<AddFromLibraryResponse>(
+ '/workspace/mcp/from-library',
+ { mcp_ids: mcpIds },
+ { agent_id: agentId, session_id: sessionId },
+ ),
+
remove: (mcpName: string, agentId: string, sessionId: string) =>
client.delete(`/workspace/mcp/${mcpName}`, {
agent_id: agentId,
@@ -23,12 +131,28 @@ export const workspaceApi = {
list: (agentId: string, sessionId: string) =>
client.get<Skill[]>('/workspace/skill', { agent_id: agentId, session_id: sessionId }),
+ /**
+ * @deprecated The path is resolved on the server. Use `upload`
+ * for a local folder or `addFromLibrary` for an installed skill.
+ */
add: (agentId: string, sessionId: string, body: AddSkillRequest) =>
client.post<void>('/workspace/skill', body, {
agent_id: agentId,
session_id: sessionId,
}),
+ /** Uploads a picked folder as a skill, reporting send progress. */
+ upload: (agentId: string, sessionId: string, files: File[], options: UploadOptions = {}) =>
+ uploadSkillXhr(agentId, sessionId, files, options),
+
+ /** Installs skills the user already has, by library record id. */
+ addFromLibrary: (agentId: string, sessionId: string, skillIds: string[]) =>
+ client.post<AddFromLibraryResponse>(
+ '/workspace/skill/from-library',
+ { skill_ids: skillIds },
+ { agent_id: agentId, session_id: sessionId },
+ ),
+
remove: (skillName: string, agentId: string, sessionId: string) =>
client.delete(`/workspace/skill/${skillName}`, {
agent_id: agentId,
diff --git a/examples/web_ui/frontend/src/components/dialog/AddMCPDialog.tsx b/examples/web_ui/frontend/src/components/dialog/AddMCPDialog.tsx
new file mode 100644
index 000000000..24eba3078
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/dialog/AddMCPDialog.tsx
@@ -0,0 +1,245 @@
+import { CircleAlert, PlusCircle } from 'lucide-react';
+import { useState } from 'react';
+import type { ReactNode } from 'react';
+
+import type { MCPClient, MCPView } from '@/api';
+import { MCPConfigForm } from '@/components/dialog/MCPConfigForm.tsx';
+import { Alert, AlertDescription } from '@/components/ui/alert.tsx';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import { Checkbox } from '@/components/ui/checkbox.tsx';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog.tsx';
+import {
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty.tsx';
+import {
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemTitle,
+} from '@/components/ui/item.tsx';
+import { Spinner } from '@/components/ui/spinner.tsx';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
+import { useMCPs } from '@/hooks/useMCPs.ts';
+import { useTranslation } from '@/i18n/useI18n';
+
+/** Ties the footer's submit button to the form in the other tab. */
+const CONFIG_FORM_ID = 'add-mcp-config-form';
+
+interface Props {
+ children: ReactNode;
+ /** Names already in this workspace, which cannot be picked again. */
+ present: Set<string>;
+ onAdd: (mcps: MCPClient[]) => Promise<void>;
+ onAddFromLibrary: (mcpIds: string[]) => Promise<void>;
+}
+
+/**
+ * Adds MCPs to a workspace, either from the ones already installed or by
+ * pasting a configuration.
+ *
+ * Two tabs rather than a chooser screen: the paths are peers, and a chooser
+ * makes picking wrong cost a round trip back. Installed comes first because
+ * reusing something already configured is the common case — pasting a
+ * config in is what you do once, per MCP, ever.
+ *
+ * The body is a fixed height and the footer sits outside the tabs, so
+ * switching tabs moves nothing except the content between them.
+ */
+export function AddMCPDialog({ children, present, onAdd, onAddFromLibrary }: Props) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [tab, setTab] = useState('installed');
+ const [picked, setPicked] = useState<Set<string>>(new Set());
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const { mcps, loading } = useMCPs();
+
+ const selectable = mcps.filter((mcp) => !present.has(mcp.name));
+
+ const toggle = (mcp: MCPView) => {
+ setPicked((prev) => {
+ const next = new Set(prev);
+ if (next.has(mcp.id)) next.delete(mcp.id);
+ else next.add(mcp.id);
+ return next;
+ });
+ };
+
+ const close = () => {
+ setOpen(false);
+ setPicked(new Set());
+ setError(null);
+ };
+
+ const handleAddPicked = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ await onAddFromLibrary([...picked]);
+ close();
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => (next ? setOpen(true) : close())}>
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{t('panel.mcp.add')}</DialogTitle>
+ <DialogDescription>{t('panel.mcp.addDescription')}</DialogDescription>
+ </DialogHeader>
+
+ <Tabs value={tab} onValueChange={setTab}>
+ <TabsList className="w-full">
+ <TabsTrigger value="installed" className="flex-1">
+ {t('panel.mcp.fromInstalled')}
+ </TabsTrigger>
+ <TabsTrigger value="configure" className="flex-1">
+ {t('panel.mcp.fromConfig')}
+ </TabsTrigger>
+ </TabsList>
+
+ {/* Fixed height on the shared container rather than per
+ tab, so the dialog does not resize as you switch. */}
+ <div className="mt-4 h-80 overflow-y-auto scroll-fade">
+ <TabsContent value="installed">
+ {loading ? (
+ <div className="flex justify-center py-10">
+ <Spinner />
+ </div>
+ ) : mcps.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <PlusCircle />
+ </EmptyMedia>
+ <EmptyTitle>
+ {t('panel.mcp.installedEmptyTitle')}
+ </EmptyTitle>
+ <EmptyDescription>
+ {t('panel.mcp.installedEmptyDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <ItemGroup className="gap-1">
+ {mcps.map((mcp) => {
+ const already = present.has(mcp.name);
+ return (
+ <Item key={mcp.id} data-disabled={already || undefined}>
+ {/* self-center overrides the base
+ class, which top-aligns media
+ once a description is present. */}
+ <Checkbox
+ checked={already || picked.has(mcp.id)}
+ disabled={already}
+ onCheckedChange={() => toggle(mcp)}
+ />
+
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={mcp.icon_url ?? undefined}
+ alt={mcp.display_name || mcp.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {(mcp.display_name || mcp.name)
+ .slice(0, 1)
+ .toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>
+ <span className="font-medium">
+ {mcp.display_name || mcp.name}
+ </span>
+ {mcp.author && (
+ <span className="text-xs text-muted-foreground">
+ @{mcp.author}
+ </span>
+ )}
+ </ItemTitle>
+ <ItemDescription className="line-clamp-1">
+ {mcp.description}
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ );
+ })}
+ </ItemGroup>
+ )}
+ </TabsContent>
+
+ <TabsContent value="configure">
+ <MCPConfigForm
+ formId={CONFIG_FORM_ID}
+ onAdd={onAdd}
+ onDone={close}
+ onBusyChange={setBusy}
+ />
+ </TabsContent>
+ </div>
+ </Tabs>
+
+ {error && (
+ <Alert variant="destructive">
+ <CircleAlert />
+ {/* One line per MCP that did not land, so the
+ joined message has to keep its newlines. */}
+ <AlertDescription className="whitespace-pre-wrap">{error}</AlertDescription>
+ </Alert>
+ )}
+
+ {/* Outside the tabs on purpose: the footer is the dialog's,
+ not either tab's, so its layout never shifts. */}
+ <DialogFooter className="sm:justify-between">
+ <span className="self-center text-xs text-muted-foreground">
+ {tab === 'installed' && selectable.length > 0
+ ? t('common.selectedCount', {
+ selected: picked.size,
+ total: selectable.length,
+ })
+ : null}
+ </span>
+ <div className="flex items-center gap-x-2">
+ <Button variant="ghost" onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ {tab === 'installed' ? (
+ <Button onClick={handleAddPicked} disabled={picked.size === 0 || busy}>
+ {busy ? <Spinner /> : <PlusCircle />}
+ {t('common.add')}
+ </Button>
+ ) : (
+ <Button type="submit" form={CONFIG_FORM_ID} disabled={busy}>
+ {busy ? <Spinner /> : <PlusCircle />}
+ {t('common.add')}
+ </Button>
+ )}
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsx b/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsx
index 75141f9c5..c358dd3b8 100644
--- a/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsx
+++ b/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsx
@@ -1,7 +1,13 @@
-import { CircleAlert, Loader2, PlusCircle } from 'lucide-react';
-import { useState, type ReactNode } from 'react';
+import { CircleAlert, FolderUp, PlusCircle } from 'lucide-react';
+import { useRef, useState } from 'react';
+import type { ReactNode } from 'react';
-import { Button } from '@/components/ui/button';
+import type { SkillView } from '@/api';
+import type { UploadOptions } from '@/api/workspace';
+import { Alert, AlertDescription } from '@/components/ui/alert.tsx';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import { Checkbox } from '@/components/ui/checkbox.tsx';
import {
Dialog,
DialogContent,
@@ -10,74 +16,325 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
-} from '@/components/ui/dialog';
-import { Input } from '@/components/ui/input';
-import { Label } from '@/components/ui/label';
+} from '@/components/ui/dialog.tsx';
+import {
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty.tsx';
+import {
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemTitle,
+} from '@/components/ui/item.tsx';
+import { Progress } from '@/components/ui/progress.tsx';
+import { Spinner } from '@/components/ui/spinner.tsx';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
+import { useSkills } from '@/hooks/useSkills.ts';
import { useTranslation } from '@/i18n/useI18n';
-interface AddSkillDialogProps {
+interface Props {
children: ReactNode;
- onAdd: (skillPath: string) => Promise<void>;
+ /** Names already in this workspace, which cannot be picked again. */
+ present: Set<string>;
+ onUpload: (files: File[], options?: UploadOptions) => Promise<void>;
+ onAddFromLibrary: (skillIds: string[]) => Promise<void>;
}
-export function AddSkillDialog({ children, onAdd }: AddSkillDialogProps) {
+/**
+ * Adds skills to a workspace, either from the ones already installed
+ * or by picking a folder off disk.
+ *
+ * Mirrors the MCP dialog: two peer tabs, a fixed-height body, and a
+ * footer outside the tabs so switching moves nothing but the content.
+ */
+export function AddSkillDialog({ children, present, onUpload, onAddFromLibrary }: Props) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
- const [skillPath, setSkillPath] = useState('');
- const [loading, setLoading] = useState(false);
+ const [tab, setTab] = useState('installed');
+ const [picked, setPicked] = useState<Set<string>>(new Set());
+ const [files, setFiles] = useState<File[]>([]);
+ const [progress, setProgress] = useState<number | null>(null);
+ const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const input = useRef<HTMLInputElement>(null);
+ const { skills, loading } = useSkills();
+
+ const selectable = skills.filter((skill) => !present.has(skill.name));
+
+ const toggle = (skill: SkillView) => {
+ setPicked((prev) => {
+ const next = new Set(prev);
+ if (next.has(skill.id)) next.delete(skill.id);
+ else next.add(skill.id);
+ return next;
+ });
+ };
+
+ const close = () => {
+ setOpen(false);
+ setPicked(new Set());
+ setFiles([]);
+ setProgress(null);
+ setError(null);
+ };
+
+ const handleAddPicked = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ await onAddFromLibrary([...picked]);
+ close();
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
- const handleSubmit = async () => {
- if (!skillPath.trim()) return;
- setLoading(true);
+ const handleUpload = async () => {
+ setBusy(true);
setError(null);
+ setProgress(0);
try {
- await onAdd(skillPath.trim());
- setSkillPath('');
- setOpen(false);
+ await onUpload(files, {
+ onProgress: ({ loaded, total }) =>
+ setProgress(total ? Math.round((loaded / total) * 100) : 0),
+ });
+ close();
} catch (e) {
setError((e as Error).message);
+ setProgress(null);
} finally {
- setLoading(false);
+ setBusy(false);
}
};
+ // The picked folder's own name, which is what the skill installs as.
+ const root = files[0]?.webkitRelativePath.split('/')[0] ?? '';
+
return (
- <Dialog open={open} onOpenChange={setOpen}>
+ <Dialog open={open} onOpenChange={(next) => (next ? setOpen(true) : close())}>
<DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent className="!w-[500px] !max-w-[500px]">
+ <DialogContent className="sm:max-w-2xl">
<DialogHeader>
- <DialogTitle>{t('dialog-skill-add.title')}</DialogTitle>
- <DialogDescription>{t('dialog-skill-add.description')}</DialogDescription>
+ <DialogTitle>{t('panel.skill.add')}</DialogTitle>
+ <DialogDescription>{t('panel.skill.addDescription')}</DialogDescription>
</DialogHeader>
- <div className="flex flex-col gap-y-2">
- <Label htmlFor="skill-path">{t('dialog-skill-add.pathLabel')}</Label>
- <Input
- id="skill-path"
- placeholder={t('dialog-skill-add.pathPlaceholder')}
- value={skillPath}
- onChange={(e) => setSkillPath(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') handleSubmit();
- }}
- />
- {error && <p className="text-destructive text-sm">{error}</p>}
- </div>
- <DialogFooter>
- <Button variant="ghost" onClick={() => setOpen(false)} disabled={loading}>
- <CircleAlert className="size-3.5" />
- {t('common.cancel')}
- </Button>
- <Button onClick={handleSubmit} disabled={loading || !skillPath.trim()}>
- {loading ? (
- <Loader2 className="size-3.5 animate-spin" />
+
+ <Tabs value={tab} onValueChange={setTab}>
+ <TabsList className="w-full">
+ <TabsTrigger value="installed" className="flex-1">
+ {t('panel.skill.fromInstalled')}
+ </TabsTrigger>
+ <TabsTrigger value="upload" className="flex-1">
+ {t('panel.skill.fromFolder')}
+ </TabsTrigger>
+ </TabsList>
+
+ {/* Fixed height on the shared container rather than per
+ tab, so the dialog does not resize as you switch. */}
+ <div className="mt-4 h-80 overflow-y-auto scroll-fade">
+ <TabsContent value="installed">
+ {loading ? (
+ <div className="flex justify-center py-10">
+ <Spinner />
+ </div>
+ ) : skills.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <PlusCircle />
+ </EmptyMedia>
+ <EmptyTitle>
+ {t('panel.skill.installedEmptyTitle')}
+ </EmptyTitle>
+ <EmptyDescription>
+ {t('panel.skill.installedEmptyDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <ItemGroup className="gap-1">
+ {skills.map((skill) => {
+ const already = present.has(skill.name);
+ return (
+ <Item
+ key={skill.id}
+ data-disabled={already || undefined}
+ >
+ <Checkbox
+ checked={already || picked.has(skill.id)}
+ disabled={already}
+ onCheckedChange={() => toggle(skill)}
+ />
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={skill.icon_url ?? undefined}
+ alt={skill.display_name || skill.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {(skill.display_name || skill.name)
+ .slice(0, 1)
+ .toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>
+ <span className="font-medium">
+ {skill.display_name || skill.name}
+ </span>
+ {skill.author && (
+ <span className="text-xs text-muted-foreground">
+ @{skill.author}
+ </span>
+ )}
+ </ItemTitle>
+ <ItemDescription className="line-clamp-1">
+ {skill.description}
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ );
+ })}
+ </ItemGroup>
+ )}
+ </TabsContent>
+
+ <TabsContent value="upload">
+ <input
+ ref={input}
+ type="file"
+ className="hidden"
+ // Non-standard but supported everywhere; React
+ // has no typing for it, hence the cast.
+ {...({
+ webkitdirectory: '',
+ directory: '',
+ } as Record<string, string>)}
+ onChange={(e) => {
+ setFiles(Array.from(e.target.files ?? []));
+ setError(null);
+ }}
+ />
+ {files.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <FolderUp />
+ </EmptyMedia>
+ <EmptyTitle>{t('panel.skill.pickFolderTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('panel.skill.pickFolderDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ <Button
+ variant="outline"
+ onClick={() => input.current?.click()}
+ >
+ <FolderUp />
+ {t('panel.skill.pickFolder')}
+ </Button>
+ </Empty>
+ ) : (
+ <ItemGroup className="gap-1">
+ <Item variant="muted">
+ <ItemMedia>
+ <FolderUp />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>
+ <span className="font-medium">{root}</span>
+ </ItemTitle>
+ <ItemDescription>
+ {t('panel.skill.fileCount', {
+ count: files.length,
+ })}
+ </ItemDescription>
+ </ItemContent>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy}
+ onClick={() => input.current?.click()}
+ >
+ {t('panel.skill.pickAnother')}
+ </Button>
+ </Item>
+ {files.map((file) => (
+ <Item key={file.webkitRelativePath} size="sm">
+ <ItemContent>
+ <ItemTitle>
+ <span className="truncate font-mono text-xs">
+ {file.webkitRelativePath}
+ </span>
+ </ItemTitle>
+ </ItemContent>
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {formatBytes(file.size)}
+ </span>
+ </Item>
+ ))}
+ </ItemGroup>
+ )}
+ </TabsContent>
+ </div>
+ </Tabs>
+
+ {progress !== null && <Progress value={progress} />}
+ {error && (
+ <Alert variant="destructive">
+ <CircleAlert />
+ {/* One line per skill that did not land, so the
+ joined message has to keep its newlines. */}
+ <AlertDescription className="whitespace-pre-wrap">{error}</AlertDescription>
+ </Alert>
+ )}
+
+ {/* Outside the tabs on purpose: the footer is the dialog's,
+ not either tab's, so its layout never shifts. */}
+ <DialogFooter className="sm:justify-between">
+ <span className="self-center text-xs text-muted-foreground">
+ {tab === 'installed' && selectable.length > 0
+ ? t('common.selectedCount', {
+ selected: picked.size,
+ total: selectable.length,
+ })
+ : null}
+ </span>
+ <div className="flex items-center gap-x-2">
+ <Button variant="ghost" onClick={close} disabled={busy}>
+ {t('common.cancel')}
+ </Button>
+ {tab === 'installed' ? (
+ <Button onClick={handleAddPicked} disabled={picked.size === 0 || busy}>
+ {busy ? <Spinner /> : <PlusCircle />}
+ {t('common.add')}
+ </Button>
) : (
- <PlusCircle className="size-3.5" />
+ <Button onClick={handleUpload} disabled={files.length === 0 || busy}>
+ {busy ? <Spinner /> : <PlusCircle />}
+ {t('common.add')}
+ </Button>
)}
- {loading ? t('dialog-mcp-create.adding') : t('common.add')}
- </Button>
+ </div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+
+/** Renders a byte count at the largest unit that keeps it readable. */
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
diff --git a/examples/web_ui/frontend/src/components/dialog/InstallMCPDialog.tsx b/examples/web_ui/frontend/src/components/dialog/InstallMCPDialog.tsx
new file mode 100644
index 000000000..2ff882133
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/dialog/InstallMCPDialog.tsx
@@ -0,0 +1,149 @@
+import { CircleAlert } from 'lucide-react';
+import { useEffect, useState } from 'react';
+
+import { hubApi, mcpApi } from '@/api';
+import type { JSONSchema, MCPCard, MCPView } from '@/api';
+import { ApiError } from '@/api/client';
+import { SchemaForm, defaultValuesFromSchema } from '@/components/form/SchemaForm.tsx';
+import type { SchemaFormValue } from '@/components/form/SchemaForm.tsx';
+import { Alert, AlertDescription } from '@/components/ui/alert.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog.tsx';
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field.tsx';
+import { Input } from '@/components/ui/input.tsx';
+import { Spinner } from '@/components/ui/spinner.tsx';
+import { useTranslation } from '@/i18n/useI18n';
+
+interface Props {
+ /** The card to install, or `null` to keep the dialog closed. */
+ card: MCPCard | null;
+ /**
+ * Set to edit an MCP already in the library instead of installing a new
+ * one: the same card, the same form, a PATCH instead of a POST.
+ */
+ editing?: MCPView | null;
+ onOpenChange: (open: boolean) => void;
+ onInstalled: () => void;
+}
+
+/**
+ * Collects a card's `inputs_schema` answers and installs — or re-keys — it.
+ *
+ * The values go straight to the server, which renders the config template.
+ * Placeholders are never substituted here, since the rendered config is what
+ * holds the secret; for the same reason the form starts blank on an edit
+ * rather than pre-filling secrets the server never sends back.
+ */
+export function InstallMCPDialog({ card, editing, onOpenChange, onInstalled }: Props) {
+ const { t } = useTranslation();
+ const [name, setName] = useState('');
+ const [values, setValues] = useState<Record<string, SchemaFormValue>>({});
+ const [installing, setInstalling] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Reset per card, so a previous card's API key is never carried over.
+ useEffect(() => {
+ if (!card) return;
+ setName(editing?.name ?? card.name);
+ setValues(defaultValuesFromSchema(card.inputs_schema as JSONSchema, new Set()));
+ setError(null);
+ }, [card, editing]);
+
+ const handleInstall = async () => {
+ if (!card) return;
+ setInstalling(true);
+ setError(null);
+ try {
+ if (editing) {
+ // Only the keys the user actually filled are sent; the
+ // server merges them over what it already holds, so leaving
+ // a secret field blank keeps the existing one.
+ const filled = Object.fromEntries(
+ Object.entries(values).filter(([, v]) => v !== undefined && v !== ''),
+ );
+ await mcpApi.update(editing.id, {
+ name,
+ ...(Object.keys(filled).length > 0 ? { values: filled } : {}),
+ });
+ } else {
+ await hubApi.mcp.install(
+ card.hub_id,
+ card.id,
+ { name: name || null, values },
+ // A 409 on the name is expected and answered inline, so
+ // the generic error toast would only duplicate it.
+ { silent: true },
+ );
+ }
+ onInstalled();
+ onOpenChange(false);
+ } catch (e) {
+ setError(e instanceof ApiError ? e.detail : (e as Error).message);
+ } finally {
+ setInstalling(false);
+ }
+ };
+
+ return (
+ <Dialog open={card !== null} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ {t(editing ? 'mcp.editTitle' : 'mcp.installTitle', {
+ name: card?.display_name || card?.name || '',
+ })}
+ </DialogTitle>
+ <DialogDescription>
+ {t(editing ? 'mcp.editDescription' : 'mcp.installDescription')}
+ </DialogDescription>
+ </DialogHeader>
+
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="install-mcp-name">{t('mcp.nameLabel')}</FieldLabel>
+ <Input
+ id="install-mcp-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={card?.name}
+ />
+ </Field>
+ </FieldGroup>
+
+ {card?.auth === 'inputs' && (
+ <SchemaForm
+ schema={card.inputs_schema as JSONSchema}
+ values={values}
+ onChange={(key, value) => setValues((prev) => ({ ...prev, [key]: value }))}
+ skipFields={new Set()}
+ idPrefix="install-mcp"
+ />
+ )}
+
+ {error && (
+ <Alert variant="destructive">
+ <CircleAlert />
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={handleInstall} disabled={installing || !name}>
+ {installing && <Spinner />}
+ {t(editing ? 'common.save' : 'mcp.install')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/dialog/MCPConfigForm.tsx b/examples/web_ui/frontend/src/components/dialog/MCPConfigForm.tsx
new file mode 100644
index 000000000..26fcacfdb
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/dialog/MCPConfigForm.tsx
@@ -0,0 +1,164 @@
+import { CircleAlert } from 'lucide-react';
+import { useState, useCallback } from 'react';
+
+import type { MCPClient, StdioMCPConfig, HttpMCPConfig } from '@/api/types';
+import { Alert, AlertDescription } from '@/components/ui/alert.tsx';
+import { Checkbox } from '@/components/ui/checkbox.tsx';
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldGroup,
+ FieldLabel,
+ FieldSet,
+} from '@/components/ui/field.tsx';
+import { InputGroup, InputGroupTextarea } from '@/components/ui/input-group.tsx';
+import { useTranslation } from '@/i18n/useI18n.ts';
+
+function parseMcpConfig(
+ raw: string,
+ keepAlive: boolean,
+ t: (key: string, opts?: Record<string, string>) => string,
+): MCPClient[] {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (e) {
+ throw new Error(t('dialog-mcp-create.parseError', { message: (e as Error).message }));
+ }
+
+ const obj = parsed as Record<string, unknown>;
+ const servers = obj.mcpServers as Record<string, Record<string, unknown>> | undefined;
+ if (!servers || typeof servers !== 'object') {
+ throw new Error(t('dialog-mcp-create.missingMcpServers'));
+ }
+
+ const entries = Object.entries(servers);
+ if (entries.length === 0) {
+ throw new Error(t('dialog-mcp-create.emptyMcpServers'));
+ }
+
+ return entries.map(([name, config]) => {
+ let mcp_config: StdioMCPConfig | HttpMCPConfig;
+ if ('url' in config) {
+ mcp_config = {
+ type: 'http_mcp',
+ url: config.url as string,
+ headers: (config.headers as Record<string, string> | undefined) ?? null,
+ timeout: (config.timeout as number | undefined) ?? null,
+ };
+ } else {
+ mcp_config = {
+ type: 'stdio_mcp',
+ command: config.command as string,
+ args: (config.args as string[] | undefined) ?? null,
+ env: (config.env as Record<string, string> | undefined) ?? null,
+ cwd: (config.cwd as string | undefined) ?? null,
+ };
+ }
+ return { name, is_stateful: keepAlive, mcp_config };
+ });
+}
+
+interface FormProps {
+ /**
+ * Ties this form to a submit button rendered outside it. The dialog's
+ * footer has to sit outside the tabs to keep its layout fixed, and the
+ * `form` attribute is how a button reaches a form it is not inside.
+ */
+ formId: string;
+ onAdd: (mcps: MCPClient[]) => Promise<void>;
+ /** Called once the add succeeds, e.g. to close the surrounding dialog. */
+ onDone?: () => void;
+ /** Reports work in flight, so the outside button can show it. */
+ onBusyChange?: (busy: boolean) => void;
+}
+
+/**
+ * The paste-a-config form — fields only; the submit button belongs to
+ * whoever renders it.
+ */
+export const MCPConfigForm = ({ formId, onAdd, onDone, onBusyChange }: FormProps) => {
+ const { t } = useTranslation();
+ const [configValue, setConfigValue] = useState('');
+ const [keepAlive, setKeepAlive] = useState(true);
+ const [errorMsg, setErrorMsg] = useState('');
+
+ const handleAdd = useCallback(async () => {
+ setErrorMsg('');
+ onBusyChange?.(true);
+ let mcpClients: MCPClient[];
+ try {
+ mcpClients = parseMcpConfig(configValue, keepAlive, t);
+ } catch (e) {
+ setErrorMsg((e as Error).message);
+ onBusyChange?.(false);
+ return;
+ }
+
+ try {
+ await onAdd(mcpClients);
+ onBusyChange?.(false);
+ setTimeout(() => onDone?.(), 1500);
+ } catch (e) {
+ // ApiErrors are already shown via the global toast in client.ts.
+ // Show only local validation errors (e.g. duplicate name) inline.
+ const isApiError = e instanceof Error && e.name === 'ApiError';
+ if (!isApiError) {
+ setErrorMsg(e instanceof Error ? e.message : String(e));
+ }
+ onBusyChange?.(false);
+ }
+ }, [configValue, keepAlive, t, onAdd, onDone, onBusyChange]);
+
+ return (
+ <form
+ id={formId}
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleAdd();
+ }}
+ >
+ <FieldSet>
+ <FieldGroup>
+ <Field>
+ <FieldContent>
+ <FieldLabel>{t('dialog-mcp-create.configLabel')}</FieldLabel>
+ </FieldContent>
+ <InputGroup>
+ <InputGroupTextarea
+ className="max-h-100"
+ value={configValue}
+ onChange={(e) => setConfigValue(e.target.value)}
+ placeholder={
+ '{\n "mcpServers": {\n "playwright": {\n "command": "npx",\n "args": ["@playwright/mcp@latest"]\n }\n }\n}'
+ }
+ />
+ </InputGroup>
+ </Field>
+ <Field orientation="horizontal">
+ <Checkbox
+ id="mcp-keep-alive"
+ checked={keepAlive}
+ onCheckedChange={(v) => setKeepAlive(v === true)}
+ />
+ <FieldContent>
+ <FieldLabel htmlFor="mcp-keep-alive">
+ {t('dialog-mcp-create.keepAlive')}
+ </FieldLabel>
+ <FieldDescription>
+ {t('dialog-mcp-create.keepAliveDesc')}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ </FieldGroup>
+ </FieldSet>
+ {errorMsg && (
+ <Alert variant="destructive">
+ <CircleAlert />
+ <AlertDescription>{errorMsg}</AlertDescription>
+ </Alert>
+ )}
+ </form>
+ );
+};
diff --git a/examples/web_ui/frontend/src/components/dialog/MCPDialog.tsx b/examples/web_ui/frontend/src/components/dialog/MCPDialog.tsx
deleted file mode 100644
index 03d6bff2a..000000000
--- a/examples/web_ui/frontend/src/components/dialog/MCPDialog.tsx
+++ /dev/null
@@ -1,206 +0,0 @@
-import { PlusCircle, Loader2, Check } from 'lucide-react';
-import { CircleAlert } from 'lucide-react';
-import { useState, useCallback } from 'react';
-import type { ReactNode } from 'react';
-
-import type { MCPClient, StdioMCPConfig, HttpMCPConfig } from '@/api/types';
-import { Alert, AlertDescription } from '@/components/ui/alert.tsx';
-import { Button } from '@/components/ui/button.tsx';
-import { Checkbox } from '@/components/ui/checkbox.tsx';
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from '@/components/ui/dialog.tsx';
-import {
- Field,
- FieldContent,
- FieldDescription,
- FieldGroup,
- FieldLabel,
- FieldSet,
-} from '@/components/ui/field.tsx';
-import { InputGroup, InputGroupTextarea } from '@/components/ui/input-group.tsx';
-import { useTranslation } from '@/i18n/useI18n.ts';
-
-type Status = 'idle' | 'loading' | 'success' | 'error';
-
-interface Props {
- children: ReactNode;
- onAdd: (mcps: MCPClient[]) => Promise<void>;
-}
-
-function parseMcpConfig(
- raw: string,
- keepAlive: boolean,
- t: (key: string, opts?: Record<string, string>) => string,
-): MCPClient[] {
- let parsed: unknown;
- try {
- parsed = JSON.parse(raw);
- } catch (e) {
- throw new Error(t('dialog-mcp-create.parseError', { message: (e as Error).message }));
- }
-
- const obj = parsed as Record<string, unknown>;
- const servers = obj.mcpServers as Record<string, Record<string, unknown>> | undefined;
- if (!servers || typeof servers !== 'object') {
- throw new Error(t('dialog-mcp-create.missingMcpServers'));
- }
-
- const entries = Object.entries(servers);
- if (entries.length === 0) {
- throw new Error(t('dialog-mcp-create.emptyMcpServers'));
- }
-
- return entries.map(([name, config]) => {
- let mcp_config: StdioMCPConfig | HttpMCPConfig;
- if ('url' in config) {
- mcp_config = {
- type: 'http_mcp',
- url: config.url as string,
- headers: (config.headers as Record<string, string> | undefined) ?? null,
- timeout: (config.timeout as number | undefined) ?? null,
- };
- } else {
- mcp_config = {
- type: 'stdio_mcp',
- command: config.command as string,
- args: (config.args as string[] | undefined) ?? null,
- env: (config.env as Record<string, string> | undefined) ?? null,
- cwd: (config.cwd as string | undefined) ?? null,
- };
- }
- return { name, is_stateful: keepAlive, mcp_config };
- });
-}
-
-export const CreateMCPDialog = ({ children, onAdd }: Props) => {
- const { t } = useTranslation();
- const [open, setOpen] = useState(false);
- const [configValue, setConfigValue] = useState('');
- const [keepAlive, setKeepAlive] = useState(true);
- const [status, setStatus] = useState<Status>('idle');
- const [errorMsg, setErrorMsg] = useState('');
-
- const reset = useCallback(() => {
- setConfigValue('');
- setKeepAlive(true);
- setStatus('idle');
- setErrorMsg('');
- }, []);
-
- const handleOpenChange = useCallback(
- (next: boolean) => {
- if (!next) reset();
- setOpen(next);
- },
- [reset],
- );
-
- const handleAdd = useCallback(async () => {
- setErrorMsg('');
- let mcpClients: MCPClient[];
- try {
- mcpClients = parseMcpConfig(configValue, keepAlive, t);
- } catch (e) {
- setErrorMsg((e as Error).message);
- setStatus('error');
- return;
- }
-
- setStatus('loading');
- try {
- await onAdd(mcpClients);
- setStatus('success');
- setTimeout(() => {
- handleOpenChange(false);
- }, 1500);
- } catch (e) {
- // ApiErrors are already shown via the global toast in client.ts.
- // Show only local validation errors (e.g. duplicate name) inline.
- const isApiError = e instanceof Error && e.name === 'ApiError';
- if (!isApiError) {
- setErrorMsg(e instanceof Error ? e.message : String(e));
- }
- setStatus('idle');
- }
- }, [configValue, keepAlive, t, onAdd, handleOpenChange]);
-
- return (
- <Dialog open={open} onOpenChange={handleOpenChange}>
- <DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent className="!w-[500px] !max-w-[500px]">
- <DialogHeader>
- <DialogTitle>{t('dialog-mcp-create.title')}</DialogTitle>
- <DialogDescription>{t('dialog-mcp-create.description')}</DialogDescription>
- </DialogHeader>
- <FieldSet>
- <FieldGroup>
- <Field>
- <FieldContent>
- <FieldLabel>{t('dialog-mcp-create.configLabel')}</FieldLabel>
- </FieldContent>
- <InputGroup>
- <InputGroupTextarea
- className="max-h-100"
- value={configValue}
- onChange={(e) => setConfigValue(e.target.value)}
- placeholder={
- '{\n "mcpServers": {\n "playwright": {\n "command": "npx",\n "args": ["@playwright/mcp@latest"]\n }\n }\n}'
- }
- />
- </InputGroup>
- </Field>
- <Field orientation="horizontal">
- <Checkbox
- id="mcp-keep-alive"
- checked={keepAlive}
- onCheckedChange={(v) => setKeepAlive(v === true)}
- />
- <FieldContent>
- <FieldLabel htmlFor="mcp-keep-alive">
- {t('dialog-mcp-create.keepAlive')}
- </FieldLabel>
- <FieldDescription>
- {t('dialog-mcp-create.keepAliveDesc')}
- </FieldDescription>
- </FieldContent>
- </Field>
- </FieldGroup>
- </FieldSet>
- {errorMsg && (
- <Alert variant="destructive">
- <CircleAlert />
- <AlertDescription>{errorMsg}</AlertDescription>
- </Alert>
- )}
- <DialogFooter>
- <Button variant="ghost" onClick={() => handleOpenChange(false)}>
- <CircleAlert className="size-3.5" />
- {t('common.cancel')}
- </Button>
- <Button
- onClick={handleAdd}
- disabled={status === 'loading' || status === 'success'}
- >
- {status === 'loading' && <Loader2 className="size-3.5 animate-spin" />}
- {status === 'success' && <Check className="size-3.5" />}
- {status !== 'loading' && status !== 'success' && (
- <PlusCircle className="size-3.5" />
- )}
- {status === 'loading'
- ? t('dialog-mcp-create.adding')
- : status === 'success'
- ? t('dialog-mcp-create.added')
- : t('common.add')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-};
diff --git a/examples/web_ui/frontend/src/components/drawer/ResourceDetailDrawer.tsx b/examples/web_ui/frontend/src/components/drawer/ResourceDetailDrawer.tsx
new file mode 100644
index 000000000..db8bd3320
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/drawer/ResourceDetailDrawer.tsx
@@ -0,0 +1,191 @@
+import { ExternalLink } from 'lucide-react';
+
+import { Markdown } from '@/components/markdown';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
+import { Badge } from '@/components/ui/badge.tsx';
+import {
+ Drawer,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+} from '@/components/ui/drawer.tsx';
+import { Separator } from '@/components/ui/separator.tsx';
+import { Spinner } from '@/components/ui/spinner.tsx';
+import { useTranslation } from '@/i18n/useI18n';
+
+/**
+ * What the drawer needs, flattened out of whichever shape it came from — a
+ * hub card or an installed record, MCP or skill. They agree on everything
+ * shown here, so one drawer serves every listing.
+ */
+export interface ResourceDetail {
+ name: string;
+ display_name?: string | null;
+ description: string;
+ tags: string[];
+ version?: string | null;
+ hub_id?: string | null;
+ author?: string | null;
+ icon_url?: string | null;
+ url?: string | null;
+ updated_at?: number | null;
+ installs?: number | null;
+ downloads?: number | null;
+ markdown?: string | null;
+}
+
+interface Props {
+ /** The resource to show, or `null` to keep the drawer closed. */
+ skill: ResourceDetail | null;
+ /** Whether the detail body is still being fetched. */
+ loading?: boolean;
+ /** The action button, which differs between browsing and the library. */
+ action: React.ReactNode;
+ /**
+ * The scrolling body: a skill's `SKILL.md`, an MCP's config template.
+ * Falls back to `skill.markdown` when omitted.
+ */
+ body?: React.ReactNode;
+ onOpenChange: (open: boolean) => void;
+}
+
+interface FactProps {
+ label: string;
+ children: React.ReactNode;
+}
+
+/** One label/value row: label left, value right. */
+function Fact({ label, children }: FactProps) {
+ return (
+ <div className="flex items-baseline justify-between gap-x-4 py-0.5">
+ <span className="text-xs text-muted-foreground shrink-0">{label}</span>
+ <span className="text-xs text-right break-words min-w-0">{children}</span>
+ </div>
+ );
+}
+
+/**
+ * The full detail of one hub card or installed resource.
+ *
+ * The facts sit in the header so they stay put; only the body below is
+ * long enough to want scrolling.
+ */
+export function ResourceDetailDrawer({
+ skill,
+ loading = false,
+ action,
+ body,
+ onOpenChange,
+}: Props) {
+ const { t } = useTranslation();
+
+ return (
+ <Drawer direction="right" open={skill !== null} onOpenChange={onOpenChange}>
+ {/* The base component pins right-side drawers to max-w-sm via a
+ data-attribute selector, so overriding needs the same form. */}
+ <DrawerContent className="data-[vaul-drawer-direction=right]:sm:max-w-2xl">
+ <DrawerHeader className="shrink-0 gap-2">
+ <div className="flex items-center gap-x-3 min-w-0">
+ <Avatar className="size-10 rounded-md">
+ <AvatarImage
+ src={skill?.icon_url ?? undefined}
+ alt={skill?.display_name || skill?.name || '?'}
+ />
+ <AvatarFallback className="rounded-md">
+ {(skill?.display_name || skill?.name || '?')
+ .slice(0, 1)
+ .toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex flex-col min-w-0">
+ <DrawerTitle className="truncate">
+ {skill?.display_name || skill?.name}
+ </DrawerTitle>
+ {skill?.author && (
+ <span className="text-xs text-muted-foreground truncate">
+ @{skill.author}
+ </span>
+ )}
+ </div>
+ </div>
+
+ <DrawerDescription>{skill?.description}</DrawerDescription>
+
+ {/* No name row — the drawer title already is the name. */}
+ <div className="flex flex-col">
+ {skill?.version && (
+ <Fact label={t('skill.versionLabel')}>{skill.version}</Fact>
+ )}
+ {skill?.hub_id && <Fact label={t('skill.hubLabel')}>{skill.hub_id}</Fact>}
+ {skill?.updated_at && (
+ <Fact label={t('skill.updatedLabel')}>
+ {/* Reported in seconds; Date wants millis. */}
+ {new Date(skill.updated_at * 1000).toLocaleDateString()}
+ </Fact>
+ )}
+ {/* Explicit null check: a hub that counts installs and
+ reports 0 is saying something, a hub that does not
+ count them at all is not. */}
+ {skill?.installs != null && (
+ <Fact label={t('skill.installsLabel')}>
+ {skill.installs.toLocaleString()}
+ </Fact>
+ )}
+ {skill?.downloads != null && (
+ <Fact label={t('skill.downloadsLabel')}>
+ {skill.downloads.toLocaleString()}
+ </Fact>
+ )}
+ {skill?.url && (
+ <Fact label={t('skill.linkLabel')}>
+ <a
+ href={skill.url}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-x-1 underline underline-offset-2"
+ >
+ {t('skill.viewOnHub')}
+ <ExternalLink className="size-3" />
+ </a>
+ </Fact>
+ )}
+ </div>
+
+ {skill && skill.tags.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {skill.tags.map((tag) => (
+ <Badge
+ key={tag}
+ variant="outline"
+ className="text-[10px] px-1 py-0"
+ >
+ {tag}
+ </Badge>
+ ))}
+ </div>
+ )}
+ </DrawerHeader>
+
+ <Separator />
+
+ <div className="flex-1 min-h-0 overflow-y-auto scroll-fade px-4 py-4">
+ {loading ? (
+ <div className="flex justify-center py-10">
+ <Spinner />
+ </div>
+ ) : body ? (
+ body
+ ) : skill?.markdown ? (
+ <Markdown>{skill.markdown}</Markdown>
+ ) : (
+ <p className="text-sm text-muted-foreground">{t('skill.noReadme')}</p>
+ )}
+ </div>
+
+ <DrawerFooter>{action}</DrawerFooter>
+ </DrawerContent>
+ </Drawer>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/hub/LoadMore.tsx b/examples/web_ui/frontend/src/components/hub/LoadMore.tsx
new file mode 100644
index 000000000..12b904c90
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/hub/LoadMore.tsx
@@ -0,0 +1,54 @@
+import { useEffect, useRef } from 'react';
+
+import { Marker, MarkerContent, MarkerIcon } from '@/components/ui/marker.tsx';
+import { Spinner } from '@/components/ui/spinner.tsx';
+import { useTranslation } from '@/i18n/useI18n';
+
+interface Props {
+ /** How many cards are already on screen, shown as a progress hint. */
+ shown: number;
+ loading: boolean;
+ onLoad: () => void;
+}
+
+/**
+ * The end-of-list marker for cursor pagination.
+ *
+ * Scrolling it into view fetches the next page, so this is a status line
+ * rather than a control: it reports how far the list has got, and spins
+ * while the page behind it is on the way.
+ */
+export function LoadMore({ shown, loading, onLoad }: Props) {
+ const { t } = useTranslation();
+ const sentinel = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const element = sentinel.current;
+ if (!element || loading) return;
+
+ // Re-subscribed whenever `onLoad` changes, which is how the newest
+ // cursor gets picked up — the callback closes over it.
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (entry.isIntersecting) onLoad();
+ },
+ // Start fetching just before the sentinel is actually visible.
+ { rootMargin: '300px' },
+ );
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [onLoad, loading]);
+
+ return (
+ <div ref={sentinel} className="py-4">
+ <Marker variant="separator" role="status">
+ {loading && (
+ <MarkerIcon>
+ <Spinner />
+ </MarkerIcon>
+ )}
+ <MarkerContent>{t('common.shownCount', { count: shown })}</MarkerContent>
+ </Marker>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/hub/ResourcePanel.tsx b/examples/web_ui/frontend/src/components/hub/ResourcePanel.tsx
new file mode 100644
index 000000000..7099ee879
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/hub/ResourcePanel.tsx
@@ -0,0 +1,61 @@
+import { Search } from 'lucide-react';
+
+import { Input } from '@/components/ui/input.tsx';
+import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from '@/components/ui/item.tsx';
+import { Separator } from '@/components/ui/separator.tsx';
+
+interface Props {
+ title: string;
+ description?: string;
+ /** Shown beside the title — a hub's icon, or a lucide glyph for "mine". */
+ icon?: React.ReactNode;
+ /** Renders a search box under the header when given. */
+ search?: { value: string; onChange: (value: string) => void; placeholder: string };
+ children: React.ReactNode;
+}
+
+/**
+ * The frame every MCP / skill hub panel sits in: a title, an optional search
+ * box, and a body.
+ *
+ * Only the body scrolls — the header and search box stay put, so the search
+ * box you are typing into cannot slide away under a long result list.
+ */
+export function ResourcePanel({ title, description, icon, search, children }: Props) {
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex shrink-0 flex-col gap-y-4 px-6 pt-6">
+ {/* Borderless Item, so the header lines up with the rows
+ below it rather than being a second layout. */}
+ <Item className="p-0">
+ {icon && <ItemMedia>{icon}</ItemMedia>}
+ <ItemContent>
+ <ItemTitle className="text-lg">{title}</ItemTitle>
+ {description ? <ItemDescription>{description}</ItemDescription> : null}
+ </ItemContent>
+ </Item>
+ <Separator />
+ {search && (
+ <div className="relative">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
+ <Input
+ className="pl-9"
+ placeholder={search.placeholder}
+ value={search.value}
+ onChange={(e) => search.onChange(e.target.value)}
+ />
+ </div>
+ )}
+ </div>
+
+ {/* min-h-0 so the flex child may shrink below its content height —
+ without it the body grows and the whole page scrolls instead.
+ scroll-fade dissolves both edges as you scroll, so cards do
+ not butt up hard against the search box or the panel bottom;
+ with no overflow it shows nothing. */}
+ <div className="flex-1 min-h-0 overflow-y-auto scroll-fade px-6 pb-6 pt-4">
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
index 60aeb9a30..e7b1018fe 100644
--- a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
+++ b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
@@ -1,4 +1,5 @@
import {
+ BookText,
BotMessageSquare,
Calendars,
Compass,
@@ -11,6 +12,7 @@ import { useOnborda } from 'onborda';
import { useNavigate, useLocation } from 'react-router-dom';
import AgentScope from '@/assets/images/agentscope.svg?react';
+import MCPSvg from '@/assets/images/mcp.svg?react';
import { CHAT_TOUR_NAME } from '@/components/tour/chatTourSteps';
import {
Sidebar,
@@ -98,6 +100,27 @@ export function AppSidebar() {
<KeyRound />
</SidebarMenuButton>
</SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ tooltip={{ children: t('common.mcp-hub'), hidden: false }}
+ // Stays lit while browsing a hub under /mcp/:hubId.
+ isActive={location.pathname.startsWith('/mcp')}
+ onClick={() => navigate('/mcp')}
+ className="px-2"
+ >
+ <MCPSvg />
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ tooltip={{ children: t('common.skill-hub'), hidden: false }}
+ isActive={location.pathname.startsWith('/skill')}
+ onClick={() => navigate('/skill')}
+ className="px-2"
+ >
+ <BookText />
+ </SidebarMenuButton>
+ </SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton
tooltip={{ children: t('common.knowledge'), hidden: false }}
diff --git a/examples/web_ui/frontend/src/components/panel/McpPanel.tsx b/examples/web_ui/frontend/src/components/panel/McpPanel.tsx
index bcbca7398..8b267d659 100644
--- a/examples/web_ui/frontend/src/components/panel/McpPanel.tsx
+++ b/examples/web_ui/frontend/src/components/panel/McpPanel.tsx
@@ -1,14 +1,37 @@
-import { PlusCircle, Search, SearchX, Trash, Unplug } from 'lucide-react';
+import {
+ ChevronRight,
+ PlusCircle,
+ Search,
+ SearchX,
+ Trash,
+ TriangleAlert,
+ Unplug,
+} from 'lucide-react';
import { useState } from 'react';
-import type { MCPClient, MCPClientStatus } from '@/api';
+import type { MCPClient, MCPClientStatus, MCPView } from '@/api';
+import { AddMCPDialog } from '@/components/dialog/AddMCPDialog.tsx';
import { DeleteDialog } from '@/components/dialog/DeleteDialog.tsx';
-import { CreateMCPDialog } from '@/components/dialog/MCPDialog.tsx';
import { PanelEmpty } from '@/components/panel/PanelEmpty';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert.tsx';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { Button } from '@/components/ui/button';
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@/components/ui/collapsible.tsx';
import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
-import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from '@/components/ui/item';
-import { Kbd, KbdGroup } from '@/components/ui/kbd';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemFooter,
+ ItemMedia,
+ ItemTitle,
+} from '@/components/ui/item';
+import { useMCPs } from '@/hooks/useMCPs.ts';
import { useTranslation } from '@/i18n/useI18n.ts';
interface McpPanelProps {
@@ -22,6 +45,7 @@ interface McpPanelProps {
* @param mcps - The MCP client configs to add.
*/
onAdd: (mcps: MCPClient[]) => Promise<void>;
+ onAddFromLibrary: (mcpIds: string[]) => Promise<void>;
/**
* Remove an MCP server by name.
*
@@ -30,6 +54,130 @@ interface McpPanelProps {
onRemove: (name: string) => Promise<void>;
}
+interface McpRowProps {
+ mcp: MCPClientStatus;
+ /**
+ * The same MCP in the user's library, matched by name. The workspace
+ * stores only what it needs to connect, so the icon, author and
+ * description come from there — and are absent for one that was never
+ * installed through the library.
+ */
+ installed?: MCPView;
+ onDelete: () => void;
+}
+
+/**
+ * One MCP in the workspace: what it is on top, what it gives you below.
+ *
+ * The tool list is worth a click but not the space — it is collapsed
+ * behind a count. A failed MCP has no tools to show, so it gets the
+ * reason instead.
+ */
+function McpRow({ mcp, installed, onDelete }: McpRowProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+
+ return (
+ <Item variant="outline" className="group/mcp">
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={installed?.icon_url ?? undefined}
+ alt={mcp.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {mcp.name.slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+
+ <ItemContent>
+ <ItemTitle>
+ <div className="truncate font-medium">{mcp.name}</div>
+ {installed?.author && (
+ <span className="text-xs text-muted-foreground">@{installed.author}</span>
+ )}
+ <span className="text-xs text-muted-foreground/50">
+ {mcp.mcp_config.type === 'stdio_mcp' ? '#stdio' : '#http'}
+ </span>
+ </ItemTitle>
+ {installed?.description && (
+ <ItemDescription className="line-clamp-1">
+ {installed.description}
+ </ItemDescription>
+ )}
+ </ItemContent>
+
+ <ItemActions>
+ <span
+ className={`size-2 shrink-0 rounded-full ${mcp.is_healthy ? 'bg-green-500' : 'bg-red-500'}`}
+ title={t(mcp.is_healthy ? 'panel.mcp.healthy' : 'panel.mcp.unhealthy')}
+ />
+ {/* Only on hover: deleting is rare, and a delete button on
+ every row competes with the status for attention. */}
+ <Button
+ variant="secondary"
+ size="icon-sm"
+ onClick={onDelete}
+ title={t('common.delete')}
+ >
+ <Trash className="size-3" />
+ </Button>
+ </ItemActions>
+
+ <ItemFooter>
+ {mcp.is_healthy ? (
+ <Collapsible open={open} onOpenChange={setOpen} className="min-w-0 basis-full">
+ <CollapsibleTrigger asChild>
+ <Button
+ variant={'secondary'}
+ className="w-full justify-between text-muted-foreground"
+ size="sm"
+ >
+ {t('panel.mcp.tools', { count: mcp.tools.length })}
+ <ChevronRight
+ className={`shrink-0 transition-transform ${open ? 'rotate-90' : ''}`}
+ />
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="flex w-full flex-col gap-y-1 px-3 py-2">
+ {mcp.tools.map((tool) => (
+ <div key={tool.name} className="flex min-w-0 flex-col gap-y-0.5">
+ {/* Names run long and are unbroken, so they must
+ be allowed to shrink before truncating. */}
+ <span
+ className="min-w-0 truncate font-mono text-xs"
+ title={tool.name}
+ >
+ {tool.name}
+ </span>
+ {tool.description && (
+ <span className="line-clamp-2 text-xs text-muted-foreground">
+ {tool.description}
+ </span>
+ )}
+ </div>
+ ))}
+ </CollapsibleContent>
+ </Collapsible>
+ ) : (
+ <Alert
+ variant="destructive"
+ className="basis-full border-red-200 bg-red-50 text-destructive dark:border-red-900 dark:bg-red-950 dark:text-red-50"
+ >
+ <TriangleAlert />
+ <AlertTitle>{t('panel.mcp.unhealthy')}</AlertTitle>
+ {mcp.error && (
+ <AlertDescription className="break-words">{mcp.error}</AlertDescription>
+ )}
+ </Alert>
+ )}
+ </ItemFooter>
+ </Item>
+ );
+}
+
/**
* Pure content body for the MCP dock panel: a search box, the list of
* equipped MCP servers, and an "Add MCP" action. Holds only local UI
@@ -41,15 +189,26 @@ interface McpPanelProps {
*
* @param mcps - The MCP servers to list.
* @param loading - Whether the list is loading.
- * @param onAdd - Add-MCP callback.
+ * @param onAdd - Add-MCP callback for a hand-written config.
+ * @param onAddFromLibrary - Add-MCP callback for library picks.
* @param onRemove - Remove-MCP callback.
* @returns The MCP panel body.
*/
-export function McpPanel({ mcps, loading = false, onAdd, onRemove }: McpPanelProps) {
+export function McpPanel({
+ mcps,
+ loading = false,
+ onAdd,
+ onAddFromLibrary,
+ onRemove,
+}: McpPanelProps) {
const { t } = useTranslation();
const [search, setSearch] = useState('');
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
+ // The workspace stores only what it takes to connect, so the display
+ // fields are looked up in the library, matched on the shared name.
+ const { mcps: library } = useMCPs();
+ const byName = new Map(library.map((mcp) => [mcp.name, mcp]));
const filtered = search
? mcps.filter((m) => m.name.toLowerCase().includes(search.toLowerCase()))
@@ -84,50 +243,31 @@ export function McpPanel({ mcps, loading = false, onAdd, onRemove }: McpPanelPro
}
/>
) : (
- <div className="flex flex-col flex-1 min-h-0 overflow-y-auto gap-y-2">
+ <div className="flex flex-col flex-1 min-h-0 gap-y-2 overflow-y-auto scroll-fade-y">
{filtered.map((mcp) => (
- <Item key={mcp.name} variant="outline">
- <ItemContent>
- <ItemTitle className="flex items-center gap-x-2">
- <span
- className={`size-2 shrink-0 rounded-full ${mcp.is_healthy ? 'bg-green-500' : 'bg-red-500'}`}
- />
- {mcp.name}
- </ItemTitle>
- <ItemDescription>
- <KbdGroup>
- <Kbd>
- {mcp.mcp_config.type === 'stdio_mcp' ? 'STDIO' : 'HTTP'}
- </Kbd>
- <Kbd>
- {t('panel.mcp.tools', { count: mcp.tools.length })}
- </Kbd>
- </KbdGroup>
- </ItemDescription>
- </ItemContent>
- <ItemActions>
- <Button
- variant="outline"
- size="icon-sm"
- onClick={() => {
- setDeleteTarget(mcp.name);
- setDeleteOpen(true);
- }}
- >
- <Trash />
- </Button>
- </ItemActions>
- </Item>
+ <McpRow
+ key={mcp.name}
+ mcp={mcp}
+ installed={byName.get(mcp.name)}
+ onDelete={() => {
+ setDeleteTarget(mcp.name);
+ setDeleteOpen(true);
+ }}
+ />
))}
</div>
)}
- <CreateMCPDialog onAdd={onAdd}>
+ <AddMCPDialog
+ present={new Set(mcps.map((m) => m.name))}
+ onAdd={onAdd}
+ onAddFromLibrary={onAddFromLibrary}
+ >
<Button variant="default">
<PlusCircle />
{t('panel.mcp.add')}
</Button>
- </CreateMCPDialog>
+ </AddMCPDialog>
<DeleteDialog
open={deleteOpen}
diff --git a/examples/web_ui/frontend/src/components/panel/SkillPanel.tsx b/examples/web_ui/frontend/src/components/panel/SkillPanel.tsx
index 98593dd17..98ae8249e 100644
--- a/examples/web_ui/frontend/src/components/panel/SkillPanel.tsx
+++ b/examples/web_ui/frontend/src/components/panel/SkillPanel.tsx
@@ -2,12 +2,22 @@ import { FileX, PlusCircle, Search, SearchX, Trash } from 'lucide-react';
import { useState } from 'react';
import type { Skill } from '@/api';
+import type { UploadOptions } from '@/api/workspace';
import { AddSkillDialog } from '@/components/dialog/AddSkillDialog.tsx';
import { DeleteDialog } from '@/components/dialog/DeleteDialog.tsx';
import { PanelEmpty } from '@/components/panel/PanelEmpty';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { Button } from '@/components/ui/button';
import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
-import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from '@/components/ui/item';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemMedia,
+ ItemTitle,
+} from '@/components/ui/item';
+import { useSkills } from '@/hooks/useSkills.ts';
import { useTranslation } from '@/i18n/useI18n.ts';
interface SkillPanelProps {
@@ -16,11 +26,18 @@ interface SkillPanelProps {
/** Whether the skill list is still loading. */
loading?: boolean;
/**
- * Add a skill to the workspace.
+ * Upload a picked folder as a skill.
*
- * @param skillPath - Path of the skill to add.
+ * @param files - The folder's files, carrying `webkitRelativePath`.
+ * @param options - Progress and abort hooks.
*/
- onAdd: (skillPath: string) => Promise<void>;
+ onUpload: (files: File[], options?: UploadOptions) => Promise<void>;
+ /**
+ * Install skills the user already has.
+ *
+ * @param skillIds - The library record ids to add.
+ */
+ onAddFromLibrary: (skillIds: string[]) => Promise<void>;
/**
* Remove a skill by name.
*
@@ -40,15 +57,26 @@ interface SkillPanelProps {
*
* @param skills - The skills to list.
* @param loading - Whether the list is loading.
- * @param onAdd - Add-skill callback.
+ * @param onUpload - Folder-upload callback.
+ * @param onAddFromLibrary - Library-install callback.
* @param onRemove - Remove-skill callback.
* @returns The skill panel body.
*/
-export function SkillPanel({ skills, loading = false, onAdd, onRemove }: SkillPanelProps) {
+export function SkillPanel({
+ skills,
+ loading = false,
+ onUpload,
+ onAddFromLibrary,
+ onRemove,
+}: SkillPanelProps) {
const { t } = useTranslation();
const [search, setSearch] = useState('');
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
+ // The workspace stores only the skill itself, so the icon and author
+ // are looked up in the library, matched on the shared name.
+ const { skills: library } = useSkills();
+ const byName = new Map(library.map((skill) => [skill.name, skill]));
const filtered = search
? skills.filter((s) => s.name.toLowerCase().includes(search.toLowerCase()))
@@ -83,31 +111,64 @@ export function SkillPanel({ skills, loading = false, onAdd, onRemove }: SkillPa
}
/>
) : (
- <div className="flex flex-col flex-1 min-h-0 overflow-y-auto gap-y-2">
- {filtered.map((skill) => (
- <Item key={skill.name} variant="outline">
- <ItemContent>
- <ItemTitle>{skill.name}</ItemTitle>
- <ItemDescription>{skill.description}</ItemDescription>
- </ItemContent>
- <ItemActions>
- <Button
- variant="outline"
- size="icon-sm"
- onClick={() => {
- setDeleteTarget(skill.name);
- setDeleteOpen(true);
- }}
- >
- <Trash />
- </Button>
- </ItemActions>
- </Item>
- ))}
+ <div className="flex flex-col flex-1 min-h-0 overflow-y-auto scroll-fade gap-y-2">
+ {filtered.map((skill) => {
+ const installed = byName.get(skill.name);
+ return (
+ <Item key={skill.name} variant="outline" className="group/skill">
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={installed?.icon_url ?? undefined}
+ alt={skill.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {skill.name.slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>
+ <span className="truncate font-medium">{skill.name}</span>
+ {installed?.author && (
+ <span className="text-xs text-muted-foreground">
+ @{installed.author}
+ </span>
+ )}
+ </ItemTitle>
+ <ItemDescription className="line-clamp-2">
+ {skill.description}
+ </ItemDescription>
+ </ItemContent>
+ <ItemActions>
+ {/* Only on hover: deleting is rare, and a
+ button on every row competes with the
+ content for attention. */}
+ <Button
+ variant="secondary"
+ size="icon-sm"
+ className="opacity-0 transition-opacity group-hover/skill:opacity-100 focus-visible:opacity-100"
+ onClick={() => {
+ setDeleteTarget(skill.name);
+ setDeleteOpen(true);
+ }}
+ title={t('common.delete')}
+ >
+ <Trash className="size-3" />
+ </Button>
+ </ItemActions>
+ </Item>
+ );
+ })}
</div>
)}
- <AddSkillDialog onAdd={onAdd}>
+ <AddSkillDialog
+ present={new Set(skills.map((s) => s.name))}
+ onUpload={onUpload}
+ onAddFromLibrary={onAddFromLibrary}
+ >
<Button variant="default">
<PlusCircle />
{t('panel.skill.add')}
diff --git a/examples/web_ui/frontend/src/components/ui/avatar.tsx b/examples/web_ui/frontend/src/components/ui/avatar.tsx
new file mode 100644
index 000000000..3c5b1ae29
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/ui/avatar.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import * as React from 'react';
+import { Avatar as AvatarPrimitive } from 'radix-ui';
+
+import { cn } from '@/lib/utils';
+
+function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
+ return (
+ <AvatarPrimitive.Root
+ data-slot="avatar"
+ className={cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', className)}
+ {...props}
+ />
+ );
+}
+
+function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
+ return (
+ <AvatarPrimitive.Image
+ data-slot="avatar-image"
+ className={cn('aspect-square size-full', className)}
+ {...props}
+ />
+ );
+}
+
+function AvatarFallback({
+ className,
+ ...props
+}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
+ return (
+ <AvatarPrimitive.Fallback
+ data-slot="avatar-fallback"
+ className={cn(
+ 'bg-muted flex size-full items-center justify-center rounded-full',
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Avatar, AvatarImage, AvatarFallback };
diff --git a/examples/web_ui/frontend/src/components/ui/progress.tsx b/examples/web_ui/frontend/src/components/ui/progress.tsx
new file mode 100644
index 000000000..439ea10e0
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/ui/progress.tsx
@@ -0,0 +1,29 @@
+import * as React from 'react';
+import { Progress as ProgressPrimitive } from 'radix-ui';
+
+import { cn } from '@/lib/utils';
+
+function Progress({
+ className,
+ value,
+ ...props
+}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
+ return (
+ <ProgressPrimitive.Root
+ data-slot="progress"
+ className={cn(
+ 'relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted',
+ className,
+ )}
+ {...props}
+ >
+ <ProgressPrimitive.Indicator
+ data-slot="progress-indicator"
+ className="size-full flex-1 bg-primary transition-all"
+ style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
+ />
+ </ProgressPrimitive.Root>
+ );
+}
+
+export { Progress };
diff --git a/examples/web_ui/frontend/src/hooks/useMCPHubCards.ts b/examples/web_ui/frontend/src/hooks/useMCPHubCards.ts
new file mode 100644
index 000000000..8ef5c2872
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useMCPHubCards.ts
@@ -0,0 +1,114 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { hubApi } from '@/api';
+import type { MCPCard } from '@/api';
+
+const PAGE_SIZE = 20;
+
+// How many consecutive empty-but-not-final pages to walk past before
+// giving up, so a hub that filters everything out cannot spin here.
+const EMPTY_PAGE_LIMIT = 5;
+
+/**
+ * Browse one MCP hub's catalog.
+ *
+ * Pagination is cursor-based, so pages accumulate — there is no jumping to
+ * page N and no total count. `hasMore` is simply "the server handed back a
+ * cursor". Changing `hubId` or `query` starts over.
+ *
+ * Responses are matched against the request that is still current before
+ * being applied, so a slow first page cannot land after a newer search.
+ *
+ * @param hubId - Hub to browse, or `null` to stay idle (e.g. while the
+ * "mine" tab is selected).
+ * @param query - Keyword filter. Note that hubs may answer a search from a
+ * separate, unpaginated endpoint, in which case `hasMore` is false even
+ * when more matches exist upstream.
+ */
+export function useMCPHubCards(hubId: string | null, query: string) {
+ const [cards, setCards] = useState<MCPCard[]>([]);
+ const [cursor, setCursor] = useState<string | null>(null);
+ // Starts true when there is something to fetch: the first paint
+ // happens before the effect fires, and a false start would flash
+ // the empty state before the spinner.
+ const [loading, setLoading] = useState(hubId !== null);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+
+ // Bumped on every hub/query change; in-flight responses for an older
+ // request id are discarded rather than applied out of order.
+ const requestId = useRef(0);
+
+ const load = useCallback(
+ async (append: boolean, fromCursor: string | null) => {
+ if (!hubId) {
+ setCards([]);
+ setCursor(null);
+ return;
+ }
+ const id = append ? requestId.current : ++requestId.current;
+ if (append) {
+ setLoadingMore(true);
+ } else {
+ setLoading(true);
+ // Nothing is known about the next page yet; leaving the
+ // previous query's cursor in place would show "Load more"
+ // while this one is still in flight.
+ setCursor(null);
+ }
+ setError(null);
+ try {
+ // A hub may hand back an empty page that still carries a
+ // cursor — ClawHub filters after fetching, so its very
+ // first page is often empty. Taking that at face value
+ // renders "nothing found" over a catalog that has plenty.
+ let next = fromCursor;
+ let fetched: MCPCard[] = [];
+ for (let attempt = 0; attempt < EMPTY_PAGE_LIMIT; attempt += 1) {
+ const page = await hubApi.mcp.listCards(hubId, {
+ q: query || undefined,
+ cursor: next ?? undefined,
+ limit: PAGE_SIZE,
+ });
+ if (id !== requestId.current) return;
+ fetched = page.cards;
+ next = page.next_cursor;
+ if (fetched.length > 0 || next === null) break;
+ }
+ setCards((prev) => (append ? [...prev, ...fetched] : fetched));
+ setCursor(next);
+ } catch (e) {
+ if (id !== requestId.current) return;
+ setError(e as Error);
+ } finally {
+ // A superseded response must not end the spinner — the
+ // request that replaced it is still in flight.
+ if (id === requestId.current) {
+ if (append) setLoadingMore(false);
+ else setLoading(false);
+ }
+ }
+ },
+ [hubId, query],
+ );
+
+ useEffect(() => {
+ load(false, null);
+ }, [load]);
+
+ /** Append the next page. No-op while a page is already in flight. */
+ const loadMore = useCallback(() => {
+ if (!cursor || loading || loadingMore) return;
+ load(true, cursor);
+ }, [cursor, loading, loadingMore, load]);
+
+ return {
+ cards,
+ loading,
+ loadingMore,
+ error,
+ hasMore: cursor !== null,
+ loadMore,
+ refetch: () => load(false, null),
+ };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useMCPHubs.ts b/examples/web_ui/frontend/src/hooks/useMCPHubs.ts
new file mode 100644
index 000000000..1a622453b
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useMCPHubs.ts
@@ -0,0 +1,37 @@
+import { useCallback, useEffect, useState } from 'react';
+
+import { hubApi } from '@/api';
+import type { HubInfo } from '@/api';
+
+/**
+ * The MCP hubs registered on the server.
+ *
+ * The list is fixed at deploy time (`create_app(mcp_hubs=[...])`), so it is
+ * fetched once and never mutated from the UI. An empty list is the normal
+ * state for a deployment that configured no hubs — not an error.
+ */
+export function useMCPHubs() {
+ const [hubs, setHubs] = useState<HubInfo[]>([]);
+ // Starts true: the first paint happens before the effect fires, and
+ // a false start would flash the empty state before the spinner.
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<Error | null>(null);
+
+ const refetch = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ setHubs(await hubApi.mcp.listHubs());
+ } catch (e) {
+ setError(e as Error);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ refetch();
+ }, [refetch]);
+
+ return { hubs, loading, error, refetch };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useMCPs.ts b/examples/web_ui/frontend/src/hooks/useMCPs.ts
new file mode 100644
index 000000000..e2e1d6a9f
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useMCPs.ts
@@ -0,0 +1,53 @@
+import { useCallback, useEffect, useState } from 'react';
+
+import { mcpApi } from '@/api';
+import type { MCPView, UpdateMCPRequest } from '@/api';
+
+/**
+ * The user's library of installed MCPs.
+ *
+ * User-level, so unlike `useWorkspace` it needs no agent/session — an empty
+ * list means the user has installed nothing yet, not that a session is
+ * missing.
+ */
+export function useMCPs() {
+ const [mcps, setMcps] = useState<MCPView[]>([]);
+ // Starts true: the first paint happens before the effect fires, and
+ // a false start would flash the empty state before the spinner.
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<Error | null>(null);
+
+ const refetch = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ setMcps(await mcpApi.list());
+ } catch (e) {
+ setError(e as Error);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ refetch();
+ }, [refetch]);
+
+ const update = useCallback(
+ async (mcpId: string, body: UpdateMCPRequest) => {
+ await mcpApi.update(mcpId, body);
+ await refetch();
+ },
+ [refetch],
+ );
+
+ const remove = useCallback(
+ async (mcpId: string) => {
+ await mcpApi.remove(mcpId);
+ await refetch();
+ },
+ [refetch],
+ );
+
+ return { mcps, loading, error, refetch, update, remove };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useResourceDrawer.ts b/examples/web_ui/frontend/src/hooks/useResourceDrawer.ts
new file mode 100644
index 000000000..4c0a25f3a
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useResourceDrawer.ts
@@ -0,0 +1,49 @@
+import { useCallback, useRef, useState } from 'react';
+
+import type { ResourceDetail } from '@/components/drawer/ResourceDetailDrawer';
+
+/**
+ * Drives the detail drawer for both a hub listing and the library.
+ *
+ * Listings carry only a summary — hubs defer the `SKILL.md` body so that
+ * browsing stays one request per page — so opening shows what is already
+ * known and fills the body in behind it. The drawer therefore never opens
+ * blank, and a failed body fetch leaves it usable rather than empty.
+ *
+ * @param load - Fetches the full record for an opened summary.
+ */
+export function useResourceDrawer(load: (skill: ResourceDetail) => Promise<ResourceDetail>) {
+ const [opened, setOpened] = useState<ResourceDetail | null>(null);
+ const [loading, setLoading] = useState(false);
+
+ // Bumped on every open; a response for a superseded one is dropped
+ // rather than replacing whatever the user is now looking at.
+ const requestId = useRef(0);
+
+ const open = useCallback(
+ async (skill: ResourceDetail) => {
+ const id = ++requestId.current;
+ setOpened(skill);
+ if (skill.markdown) return;
+
+ setLoading(true);
+ try {
+ const full = await load(skill);
+ if (id === requestId.current) setOpened(full);
+ } catch {
+ // The summary is already on screen; keep it.
+ } finally {
+ if (id === requestId.current) setLoading(false);
+ }
+ },
+ [load],
+ );
+
+ const close = useCallback(() => {
+ requestId.current += 1;
+ setOpened(null);
+ setLoading(false);
+ }, []);
+
+ return { opened, loading, open, close };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useSkillHubCards.ts b/examples/web_ui/frontend/src/hooks/useSkillHubCards.ts
new file mode 100644
index 000000000..40afa63f1
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useSkillHubCards.ts
@@ -0,0 +1,114 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { hubApi } from '@/api';
+import type { SkillCard } from '@/api';
+
+const PAGE_SIZE = 20;
+
+// How many consecutive empty-but-not-final pages to walk past before
+// giving up, so a hub that filters everything out cannot spin here.
+const EMPTY_PAGE_LIMIT = 5;
+
+/**
+ * Browse one skill hub's catalog.
+ *
+ * Pagination is cursor-based, so pages accumulate — there is no jumping to
+ * page N and no total count. `hasMore` is simply "the server handed back a
+ * cursor". Changing `hubId` or `query` starts over.
+ *
+ * Responses are matched against the request that is still current before
+ * being applied, so a slow first page cannot land after a newer search.
+ *
+ * @param hubId - Hub to browse, or `null` to stay idle (e.g. while the
+ * "mine" tab is selected).
+ * @param query - Keyword filter. Note that hubs may answer a search from a
+ * separate, unpaginated endpoint, in which case `hasMore` is false even
+ * when more matches exist upstream.
+ */
+export function useSkillHubCards(hubId: string | null, query: string) {
+ const [cards, setCards] = useState<SkillCard[]>([]);
+ const [cursor, setCursor] = useState<string | null>(null);
+ // Starts true when there is something to fetch: the first paint
+ // happens before the effect fires, and a false start would flash
+ // the empty state before the spinner.
+ const [loading, setLoading] = useState(hubId !== null);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+
+ // Bumped on every hub/query change; in-flight responses for an older
+ // request id are discarded rather than applied out of order.
+ const requestId = useRef(0);
+
+ const load = useCallback(
+ async (append: boolean, fromCursor: string | null) => {
+ if (!hubId) {
+ setCards([]);
+ setCursor(null);
+ return;
+ }
+ const id = append ? requestId.current : ++requestId.current;
+ if (append) {
+ setLoadingMore(true);
+ } else {
+ setLoading(true);
+ // Nothing is known about the next page yet; leaving the
+ // previous query's cursor in place would show "Load more"
+ // while this one is still in flight.
+ setCursor(null);
+ }
+ setError(null);
+ try {
+ // A hub may hand back an empty page that still carries a
+ // cursor — ClawHub filters after fetching, so its very
+ // first page is often empty. Taking that at face value
+ // renders "nothing found" over a catalog that has plenty.
+ let next = fromCursor;
+ let fetched: SkillCard[] = [];
+ for (let attempt = 0; attempt < EMPTY_PAGE_LIMIT; attempt += 1) {
+ const page = await hubApi.skill.listCards(hubId, {
+ q: query || undefined,
+ cursor: next ?? undefined,
+ limit: PAGE_SIZE,
+ });
+ if (id !== requestId.current) return;
+ fetched = page.cards;
+ next = page.next_cursor;
+ if (fetched.length > 0 || next === null) break;
+ }
+ setCards((prev) => (append ? [...prev, ...fetched] : fetched));
+ setCursor(next);
+ } catch (e) {
+ if (id !== requestId.current) return;
+ setError(e as Error);
+ } finally {
+ // A superseded response must not end the spinner — the
+ // request that replaced it is still in flight.
+ if (id === requestId.current) {
+ if (append) setLoadingMore(false);
+ else setLoading(false);
+ }
+ }
+ },
+ [hubId, query],
+ );
+
+ useEffect(() => {
+ load(false, null);
+ }, [load]);
+
+ /** Append the next page. No-op while a page is already in flight. */
+ const loadMore = useCallback(() => {
+ if (!cursor || loading || loadingMore) return;
+ load(true, cursor);
+ }, [cursor, loading, loadingMore, load]);
+
+ return {
+ cards,
+ loading,
+ loadingMore,
+ error,
+ hasMore: cursor !== null,
+ loadMore,
+ refetch: () => load(false, null),
+ };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useSkillHubs.ts b/examples/web_ui/frontend/src/hooks/useSkillHubs.ts
new file mode 100644
index 000000000..2bb6c9e09
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useSkillHubs.ts
@@ -0,0 +1,37 @@
+import { useCallback, useEffect, useState } from 'react';
+
+import { hubApi } from '@/api';
+import type { HubInfo } from '@/api';
+
+/**
+ * The skill hubs registered on the server.
+ *
+ * The list is fixed at deploy time (`create_app(skill_hubs=[...])`), so it is
+ * fetched once and never mutated from the UI. An empty list is the normal
+ * state for a deployment that configured no hubs — not an error.
+ */
+export function useSkillHubs() {
+ const [hubs, setHubs] = useState<HubInfo[]>([]);
+ // Starts true: the first paint happens before the effect fires, and
+ // a false start would flash the empty state before the spinner.
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<Error | null>(null);
+
+ const refetch = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ setHubs(await hubApi.skill.listHubs());
+ } catch (e) {
+ setError(e as Error);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ refetch();
+ }, [refetch]);
+
+ return { hubs, loading, error, refetch };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useSkills.ts b/examples/web_ui/frontend/src/hooks/useSkills.ts
index 25ed59f2b..a5e955dbe 100644
--- a/examples/web_ui/frontend/src/hooks/useSkills.ts
+++ b/examples/web_ui/frontend/src/hooks/useSkills.ts
@@ -1,59 +1,45 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useCallback, useEffect, useState } from 'react';
-import { workspaceApi } from '../api';
-import type { Skill } from '../api';
+import { skillApi } from '@/api';
+import type { SkillView } from '@/api';
/**
- * Manages skills available in a session's workspace.
- * Re-fetches whenever agentId or sessionId changes.
+ * The user's library of installed skills.
*
- * @param agentId - The owning agent. Pass null to skip fetching.
- * @param sessionId - The target session. Pass null to skip fetching.
+ * User-level, so unlike `useWorkspace` it needs no agent/session — an empty
+ * list means the user has installed nothing yet, not that a session is
+ * missing.
*/
-export function useSkills(agentId: string | null, sessionId: string | null) {
- const [skills, setSkills] = useState<Skill[]>([]);
- const [loading, setLoading] = useState(false);
+export function useSkills() {
+ const [skills, setSkills] = useState<SkillView[]>([]);
+ // Starts true: the first paint happens before the effect fires, and
+ // a false start would flash the empty state before the spinner.
+ const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const refetch = useCallback(async () => {
- if (!agentId || !sessionId) {
- setSkills([]);
- return;
- }
setLoading(true);
setError(null);
try {
- setSkills(await workspaceApi.skill.list(agentId, sessionId));
+ setSkills(await skillApi.list());
} catch (e) {
setError(e as Error);
} finally {
setLoading(false);
}
- }, [agentId, sessionId]);
+ }, []);
useEffect(() => {
refetch();
}, [refetch]);
- /** Adds a skill from the given path and refreshes the list. */
- const add = useCallback(
- async (skillPath: string) => {
- if (!agentId || !sessionId) throw new Error('No agent/session selected');
- await workspaceApi.skill.add(agentId, sessionId, { skill_path: skillPath });
- await refetch();
- },
- [agentId, sessionId, refetch],
- );
-
- /** Removes a skill by name and refreshes the list. */
const remove = useCallback(
- async (skillName: string) => {
- if (!agentId || !sessionId) throw new Error('No agent/session selected');
- await workspaceApi.skill.remove(skillName, agentId, sessionId);
+ async (skillId: string) => {
+ await skillApi.remove(skillId);
await refetch();
},
- [agentId, sessionId, refetch],
+ [refetch],
);
- return { skills, loading, error, refetch, add, remove };
+ return { skills, loading, error, refetch, remove };
}
diff --git a/examples/web_ui/frontend/src/hooks/useWorkspace.ts b/examples/web_ui/frontend/src/hooks/useWorkspace.ts
index 0dd8bfcea..0ad9c0cde 100644
--- a/examples/web_ui/frontend/src/hooks/useWorkspace.ts
+++ b/examples/web_ui/frontend/src/hooks/useWorkspace.ts
@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import { workspaceApi } from '@/api';
import type { MCPClient, MCPClientStatus, Skill } from '@/api';
+import type { UploadOptions } from '@/api/workspace';
export function useWorkspace(agentId: string | null, sessionId: string | null) {
const [mcps, setMcps] = useState<MCPClientStatus[]>([]);
@@ -72,6 +73,21 @@ export function useWorkspace(agentId: string | null, sessionId: string | null) {
[agentId, sessionId, mcps, refetch],
);
+ const addMcpsFromLibrary = useCallback(
+ async (mcpIds: string[]) => {
+ if (!agentId || !sessionId) throw new Error('No agent/session selected');
+ const result = await workspaceApi.mcp.addFromLibrary(agentId, sessionId, mcpIds);
+ await refetch();
+ // Reported per MCP, so a partial success is still a success for
+ // what landed; surface only what did not.
+ const failures = Object.entries(result.failed);
+ if (failures.length > 0) {
+ throw new Error(failures.map(([name, why]) => `${name}: ${why}`).join('\n'));
+ }
+ },
+ [agentId, sessionId, refetch],
+ );
+
const removeMcp = useCallback(
async (mcpName: string) => {
if (!agentId || !sessionId) throw new Error('No agent/session selected');
@@ -81,15 +97,30 @@ export function useWorkspace(agentId: string | null, sessionId: string | null) {
[agentId, sessionId, refetch],
);
- const addSkill = useCallback(
- async (skillPath: string) => {
+ const uploadSkill = useCallback(
+ async (files: File[], options: UploadOptions = {}) => {
if (!agentId || !sessionId) throw new Error('No agent/session selected');
- await workspaceApi.skill.add(agentId, sessionId, { skill_path: skillPath });
+ await workspaceApi.skill.upload(agentId, sessionId, files, options);
await refetchSkills();
},
[agentId, sessionId, refetchSkills],
);
+ const addSkillsFromLibrary = useCallback(
+ async (skillIds: string[]) => {
+ if (!agentId || !sessionId) throw new Error('No agent/session selected');
+ const result = await workspaceApi.skill.addFromLibrary(agentId, sessionId, skillIds);
+ await refetchSkills();
+ // Reported per skill, so a partial success is still a success
+ // for what landed; surface only what did not.
+ const failures = Object.entries(result.failed);
+ if (failures.length > 0) {
+ throw new Error(failures.map(([name, why]) => `${name}: ${why}`).join('\n'));
+ }
+ },
+ [agentId, sessionId, refetchSkills],
+ );
+
const removeSkill = useCallback(
async (skillName: string) => {
if (!agentId || !sessionId) throw new Error('No agent/session selected');
@@ -105,10 +136,12 @@ export function useWorkspace(agentId: string | null, sessionId: string | null) {
error,
refetch,
addMcps,
+ addMcpsFromLibrary,
removeMcp,
skills,
skillsLoading,
- addSkill,
+ uploadSkill,
+ addSkillsFromLibrary,
removeSkill,
};
}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index d93e27452..206e5c792 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -19,6 +19,8 @@
"interrupted": "Interrupted",
"knowledge": "Knowledge Bases",
"loading": "Loading...",
+ "shownCount": "{{count}} shown",
+ "selectedCount": "{{selected}} of {{total}} selected",
"model": "Model",
"name": "Name",
"no": "No",
@@ -43,7 +45,12 @@
"time": "Time",
"yes": "Yes",
"deleteTitle": "Delete {{entity}} \"{{name}}\"?",
- "deleteDescription": "This action cannot be undone."
+ "deleteDescription": "This action cannot be undone.",
+ "mcp-hub": "MCP Hub",
+ "mine": "Mine",
+ "my-mcp": "Installed MCPs",
+ "skill-hub": "Skill Hub",
+ "my-skill": "Installed skills"
},
"error": {
"description": "The page hit an unexpected error. You can retry or go back home.",
@@ -121,6 +128,7 @@
"upstream": "The upstream model service returned an error.",
"connection": "Could not reach the model service — network error or timeout.",
"internal": "An unexpected internal error occurred.",
+ "setup": "The session could not be prepared — check the agent's model, tools and knowledge bases.",
"unknown": "The reply failed with an unknown error."
}
},
@@ -410,13 +418,9 @@
"dont_ask-tooltip": "Convert all ASK decisions to DENY; suitable for scheduled tasks or background execution when user is unavailable"
},
"dialog-mcp-create": {
- "title": "Add MCP Servers",
- "description": "Add new MCP server(s) by configuration.",
"configLabel": "MCP Configuration",
"keepAlive": "Keep Alive",
"keepAliveDesc": "Maintain state across interactions. Enable for browser-use or other long-running MCPs.",
- "adding": "Adding…",
- "added": "Added",
"parseError": "Invalid JSON configuration: {{message}}",
"missingMcpServers": "Configuration must contain a \"mcpServers\" object.",
"emptyMcpServers": "No MCP servers found in configuration."
@@ -426,12 +430,6 @@
"skillEntity": "skill",
"skillDescription": "Are you sure you want to remove this skill from the workspace?"
},
- "dialog-skill-add": {
- "title": "Add skill",
- "description": "Enter the path to a skill directory to add it to the workspace.",
- "pathLabel": "Skill path",
- "pathPlaceholder": "/path/to/skill"
- },
"schedule": {
"calendar": "Calendar",
"createSchedule": {
@@ -553,9 +551,16 @@
"description": "The MCP servers equipped in the workspace.",
"searchPlaceholder": "Search MCP in the workspace",
"add": "Add MCP",
+ "addDescription": "Reuse one you have already installed, or paste a configuration.",
+ "fromConfig": "From configuration",
"tools": "{{count}} tools",
+ "unhealthy": "This MCP could not be reached",
+ "healthy": "Connected",
"emptyTitle": "No MCP servers",
- "emptyDescription": "Add an MCP server to equip the workspace with tools."
+ "emptyDescription": "Add an MCP server to equip the workspace with tools.",
+ "fromInstalled": "Installed MCPs",
+ "installedEmptyTitle": "Nothing installed yet",
+ "installedEmptyDescription": "Install one from the MCP Hub, or paste a configuration."
},
"skill": {
"title": "Skills",
@@ -563,7 +568,17 @@
"searchPlaceholder": "Search skills in the workspace",
"add": "Add Skill",
"emptyTitle": "No skills",
- "emptyDescription": "Add a skill to equip the workspace."
+ "emptyDescription": "Add a skill to equip the workspace.",
+ "addDescription": "Pick from your installed skills, or upload a local folder.",
+ "fromInstalled": "From installed",
+ "fromFolder": "Upload a folder",
+ "installedEmptyTitle": "No installed skills yet",
+ "installedEmptyDescription": "Install one from the skill hub, then add it here.",
+ "pickFolderTitle": "Pick a skill folder",
+ "pickFolderDescription": "The folder must hold a SKILL.md at its root.",
+ "pickFolder": "Choose folder",
+ "pickAnother": "Choose another",
+ "fileCount": "{{count}} files"
},
"knowledge": {
"title": "Knowledge Bases",
@@ -600,5 +615,59 @@
"running": "Running",
"idle": "Idle",
"missingSession": "(no session)"
+ },
+ "mcp": {
+ "subtitle": "Browse and install MCP servers",
+ "hubsLabel": "Hubs",
+ "searchPlaceholder": "Search this hub",
+ "mineSearchPlaceholder": "Search your MCPs",
+ "noHubsTitle": "No hubs available",
+ "noHubsDescription": "Ask your administrator to add one.",
+ "noCardsTitle": "Nothing found",
+ "noCardsDescription": "Try a different keyword.",
+ "mineDescription": "The MCP servers you have installed",
+ "mineEmptyTitle": "No MCP servers yet",
+ "mineEmptyDescription": "Install one from a hub on the left.",
+ "needsConfig": "Needs configuration",
+ "stateful": "Stateful",
+ "configLabel": "Configuration",
+ "install": "Install",
+ "installed": "Installed",
+ "installTitle": "Install {{name}}",
+ "installDescription": "Adds it to your MCPs. Pick a session to use it in afterwards.",
+ "editTitle": "Edit {{name}}",
+ "editDescription": "Leave a secret blank to keep the one already stored.",
+ "nameLabel": "Name",
+ "loadFailedTitle": "Couldn't reach the server",
+ "loadFailedDescription": "Check the server URL and that the service is running.",
+ "retry": "Retry"
+ },
+ "skill": {
+ "subtitle": "Browse and install skills",
+ "hubsLabel": "Hubs",
+ "searchPlaceholder": "Search this hub",
+ "mineSearchPlaceholder": "Search your skills",
+ "noHubsTitle": "No hubs available",
+ "noHubsDescription": "Ask your administrator to add one.",
+ "noCardsTitle": "Nothing found",
+ "noCardsDescription": "Try a different keyword.",
+ "mineDescription": "The skills you have installed",
+ "mineEmptyTitle": "No skills yet",
+ "mineEmptyDescription": "Install one from a hub on the left.",
+ "install": "Install",
+ "installed": "Installed",
+ "versionLabel": "Version",
+ "hubLabel": "Hub",
+ "updatedLabel": "Updated",
+ "updatedAgo": "Updated {{ago}} ago",
+ "updatedRecently": "Just updated",
+ "installsLabel": "Installs",
+ "downloadsLabel": "Downloads",
+ "linkLabel": "Page",
+ "viewOnHub": "View on hub",
+ "noReadme": "This skill ships no SKILL.md body.",
+ "loadFailedTitle": "Couldn't reach the server",
+ "loadFailedDescription": "Check the server URL and that the service is running.",
+ "retry": "Retry"
}
}
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index 57bdbe298..5fa72102f 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -19,6 +19,8 @@
"interrupted": "已中断",
"knowledge": "知识库",
"loading": "加载中...",
+ "shownCount": "已显示 {{count}} 个",
+ "selectedCount": "已选中 {{selected}} 个,共 {{total}} 个",
"model": "模型",
"name": "名称",
"no": "否",
@@ -43,7 +45,12 @@
"time": "时间",
"yes": "是",
"deleteTitle": "删除{{entity}} \"{{name}}\"?",
- "deleteDescription": "此操作无法撤销。"
+ "deleteDescription": "此操作无法撤销。",
+ "mcp-hub": "MCP 中心",
+ "mine": "我的",
+ "my-mcp": "已安装的 MCP",
+ "skill-hub": "技能中心",
+ "my-skill": "已安装的技能"
},
"error": {
"description": "页面遇到意外错误。你可以重试或返回首页。",
@@ -121,6 +128,7 @@
"upstream": "上游模型服务返回了错误。",
"connection": "无法连接模型服务 —— 网络错误或超时。",
"internal": "发生了未预期的内部错误。",
+ "setup": "会话准备失败 —— 请检查该 agent 的模型、工具和知识库配置。",
"unknown": "回复因未知错误失败。"
}
},
@@ -410,13 +418,9 @@
"dont_ask-tooltip": "将所有 ASK 决策转为 DENY,适合定时任务或用户不在场时的后台执行"
},
"dialog-mcp-create": {
- "title": "添加 MCP 服务器",
- "description": "通过配置添加新的 MCP 服务器。",
"configLabel": "MCP 配置",
"keepAlive": "保持连接",
"keepAliveDesc": "在交互间保持状态。适用于浏览器操作或其他长时间运行的 MCP。",
- "adding": "添加中…",
- "added": "已添加",
"parseError": "JSON 配置无效:{{message}}",
"missingMcpServers": "配置中必须包含 \"mcpServers\" 对象。",
"emptyMcpServers": "配置中未找到 MCP 服务器。"
@@ -426,12 +430,6 @@
"skillEntity": "技能",
"skillDescription": "确定要将该技能从工作区中移除吗?"
},
- "dialog-skill-add": {
- "title": "添加技能",
- "description": "输入技能目录的路径以添加到工作区。",
- "pathLabel": "技能路径",
- "pathPlaceholder": "/path/to/skill"
- },
"schedule": {
"calendar": "日历",
"createSchedule": {
@@ -553,9 +551,16 @@
"description": "工作区中配置的 MCP 服务器。",
"searchPlaceholder": "在工作区中搜索 MCP",
"add": "添加 MCP",
+ "addDescription": "复用已安装的 MCP,或粘贴一份配置。",
+ "fromConfig": "从 configuration 导入",
"tools": "{{count}} 个工具",
+ "unhealthy": "该 MCP 无法连接",
+ "healthy": "连接正常",
"emptyTitle": "暂无 MCP 服务器",
- "emptyDescription": "添加 MCP 服务器为工作区配备工具。"
+ "emptyDescription": "添加 MCP 服务器为工作区配备工具。",
+ "fromInstalled": "导入已安装的 MCP",
+ "installedEmptyTitle": "还没有安装任何 MCP",
+ "installedEmptyDescription": "去 MCP 中心安装一个,或在这里粘贴配置。"
},
"skill": {
"title": "技能",
@@ -563,7 +568,17 @@
"searchPlaceholder": "在工作区中搜索技能",
"add": "添加技能",
"emptyTitle": "暂无技能",
- "emptyDescription": "添加技能为工作区配备能力。"
+ "emptyDescription": "添加技能为工作区配备能力。",
+ "addDescription": "从已安装的 Skill 中选择,或上传本地文件夹。",
+ "fromInstalled": "导入已安装 Skill",
+ "fromFolder": "从文件夹上传",
+ "installedEmptyTitle": "还没有已安装的 Skill",
+ "installedEmptyDescription": "先到 Skill 市场安装,再从这里加入工作区。",
+ "pickFolderTitle": "选择一个 Skill 文件夹",
+ "pickFolderDescription": "文件夹根目录需要包含 SKILL.md。",
+ "pickFolder": "选择文件夹",
+ "pickAnother": "重新选择",
+ "fileCount": "{{count}} 个文件"
},
"knowledge": {
"title": "知识库",
@@ -600,5 +615,59 @@
"running": "运行中",
"idle": "空闲",
"missingSession": "(无会话)"
+ },
+ "mcp": {
+ "subtitle": "浏览并安装 MCP 服务",
+ "hubsLabel": "来源",
+ "searchPlaceholder": "在该来源中搜索",
+ "mineSearchPlaceholder": "搜索你的 MCP",
+ "noHubsTitle": "暂无可用来源",
+ "noHubsDescription": "请联系管理员添加。",
+ "noCardsTitle": "没有找到内容",
+ "noCardsDescription": "换个关键词试试。",
+ "mineDescription": "你已安装的 MCP 服务",
+ "mineEmptyTitle": "还没有 MCP 服务",
+ "mineEmptyDescription": "从左侧的来源中安装一个。",
+ "needsConfig": "需要配置",
+ "stateful": "有状态",
+ "configLabel": "配置",
+ "install": "安装",
+ "installed": "已安装",
+ "installTitle": "安装 {{name}}",
+ "installDescription": "添加到你的 MCP 中,之后可在会话里启用。",
+ "editTitle": "编辑 {{name}}",
+ "editDescription": "密钥留空则沿用已保存的值。",
+ "nameLabel": "名称",
+ "loadFailedTitle": "无法连接服务",
+ "loadFailedDescription": "请检查服务地址,以及服务是否已启动。",
+ "retry": "重试"
+ },
+ "skill": {
+ "subtitle": "浏览并安装技能",
+ "hubsLabel": "来源",
+ "searchPlaceholder": "在该来源中搜索",
+ "mineSearchPlaceholder": "搜索你的技能",
+ "noHubsTitle": "暂无可用来源",
+ "noHubsDescription": "请联系管理员添加。",
+ "noCardsTitle": "没有找到内容",
+ "noCardsDescription": "换个关键词试试。",
+ "mineDescription": "你已安装的技能",
+ "mineEmptyTitle": "还没有技能",
+ "mineEmptyDescription": "从左侧的来源中安装一个。",
+ "install": "安装",
+ "installed": "已安装",
+ "versionLabel": "版本",
+ "hubLabel": "来源",
+ "updatedLabel": "更新于",
+ "updatedAgo": "{{ago}}前更新",
+ "updatedRecently": "刚刚更新",
+ "installsLabel": "安装量",
+ "downloadsLabel": "下载量",
+ "linkLabel": "页面",
+ "viewOnHub": "在来源站点查看",
+ "noReadme": "该技能没有提供 SKILL.md 正文。",
+ "loadFailedTitle": "无法连接服务",
+ "loadFailedDescription": "请检查服务地址,以及服务是否已启动。",
+ "retry": "重试"
}
}
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index dbff0c4b4..f8f071628 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -165,10 +165,12 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
mcps,
loading: mcpsLoading,
addMcps,
+ addMcpsFromLibrary,
removeMcp,
skills,
skillsLoading,
- addSkill,
+ uploadSkill,
+ addSkillsFromLibrary,
removeSkill,
} = useWorkspace(agentId, sessionId);
const { knowledgeBases, loading: knowledgeBasesLoading } = useKnowledgeBases();
@@ -233,6 +235,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
mcps={mcps}
loading={mcpsLoading}
onAdd={addMcps}
+ onAddFromLibrary={addMcpsFromLibrary}
onRemove={removeMcp}
/>
),
@@ -244,7 +247,8 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
<SkillPanel
skills={skills}
loading={skillsLoading}
- onAdd={addSkill}
+ onUpload={uploadSkill}
+ onAddFromLibrary={addSkillsFromLibrary}
onRemove={removeSkill}
/>
),
@@ -300,10 +304,12 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
mcps,
mcpsLoading,
addMcps,
+ addMcpsFromLibrary,
removeMcp,
skills,
skillsLoading,
- addSkill,
+ uploadSkill,
+ addSkillsFromLibrary,
removeSkill,
permissionContext,
knowledgeBases,
diff --git a/examples/web_ui/frontend/src/pages/mcp/index.tsx b/examples/web_ui/frontend/src/pages/mcp/index.tsx
new file mode 100644
index 000000000..ad1d09f95
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/mcp/index.tsx
@@ -0,0 +1,625 @@
+import { Blocks, Check, Download, Pencil, Store, Trash2, TriangleAlert } from 'lucide-react';
+import { Fragment, useCallback, useEffect, useState } from 'react';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import { hubApi } from '@/api';
+import type { HubInfo, MCPCard, MCPView } from '@/api';
+import { InstallMCPDialog } from '@/components/dialog/InstallMCPDialog.tsx';
+import { ResourceDetailDrawer } from '@/components/drawer/ResourceDetailDrawer.tsx';
+import { LoadMore } from '@/components/hub/LoadMore.tsx';
+import { ResourcePanel } from '@/components/hub/ResourcePanel.tsx';
+import { Markdown } from '@/components/markdown';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
+import { Badge } from '@/components/ui/badge.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty.tsx';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemSeparator,
+ ItemTitle,
+} from '@/components/ui/item.tsx';
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarGroup,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarMenu,
+ SidebarMenuButton,
+ SidebarMenuItem,
+} from '@/components/ui/sidebar.tsx';
+import { Spinner } from '@/components/ui/spinner.tsx';
+import { useMCPHubCards } from '@/hooks/useMCPHubCards.ts';
+import { useMCPHubs } from '@/hooks/useMCPHubs.ts';
+import { useMCPs } from '@/hooks/useMCPs.ts';
+import { useResourceDrawer } from '@/hooks/useResourceDrawer.ts';
+import { useTranslation } from '@/i18n/useI18n';
+import { formatTime } from '@/utils/common';
+
+/**
+ * The drawer body: the server's README where a skill shows its `SKILL.md`,
+ * plus what it will actually be installed as.
+ *
+ * The `${...}` placeholders are left in — they are resolved server-side
+ * from the install form, so this is the template, never the filled-in
+ * config with its secrets.
+ */
+function MCPDetailBody({ card }: { card: MCPCard | null }) {
+ const { t } = useTranslation();
+
+ if (!card) return null;
+
+ return (
+ <div className="flex flex-col gap-y-6">
+ <div className="flex flex-col gap-y-2">
+ <span className="text-xs text-muted-foreground">{t('mcp.configLabel')}</span>
+ <pre className="overflow-x-auto rounded-md bg-muted p-3 text-xs">
+ {JSON.stringify(card.config_template, null, 2)}
+ </pre>
+ </div>
+ {card.readme && <Markdown>{card.readme}</Markdown>}
+ </div>
+ );
+}
+
+interface CardItemProps {
+ card: MCPCard;
+ installed: boolean;
+ /** "Now" in epoch seconds, pinned by the panel so every row in a
+ * render agrees and the age does not shift on unrelated re-renders. */
+ now: number;
+ onInstall: () => void;
+ onOpen: () => void;
+}
+
+function CardItem({ card, installed, now, onInstall, onOpen }: CardItemProps) {
+ const { t } = useTranslation();
+
+ return (
+ <Item className="cursor-pointer hover:bg-accent/50" onClick={onOpen}>
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={card.icon_url ?? undefined}
+ alt={card.display_name || card.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {(card.display_name || card.name).slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+
+ <ItemContent>
+ {/* Name, author, tags — each step lighter than the last, so
+ the eye lands on the name first. */}
+ <ItemTitle>
+ <span className="font-medium">{card.display_name || card.name}</span>
+ {card.author && (
+ <span className="text-xs text-muted-foreground">@{card.author}</span>
+ )}
+ {card.auth === 'inputs' && (
+ <Badge variant="outline" className="text-[10px] px-1 py-0">
+ {t('mcp.needsConfig')}
+ </Badge>
+ )}
+ {card.tags.slice(0, 4).map((tag) => (
+ <span key={tag} className="text-xs text-muted-foreground/60">
+ #{tag}
+ </span>
+ ))}
+ </ItemTitle>
+ <ItemDescription className="line-clamp-1">{card.description}</ItemDescription>
+ </ItemContent>
+
+ <ItemActions className="flex-col items-end">
+ {/* Rendered even when empty: a missing timestamp would
+ otherwise drop this row and slide the counter up, so
+ rows would not line up with each other. */}
+ <span className="h-4 text-xs text-muted-foreground whitespace-nowrap">
+ {card.updated_at
+ ? now - card.updated_at < 3600
+ ? t('skill.updatedRecently')
+ : t('skill.updatedAgo', {
+ ago: formatTime(now - card.updated_at, {
+ leadingUnitOnly: true,
+ }),
+ })
+ : null}
+ </span>
+ <div className="flex h-8 items-center gap-2">
+ {/* Explicit null check: a hub reporting 0 installs is
+ saying something, one that does not count them is not. */}
+ {card.installs != null && (
+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
+ <Download className="size-3" />
+ {card.installs.toLocaleString()}
+ </span>
+ )}
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ disabled={installed}
+ // Installing straight from the row must not also
+ // open the drawer behind it.
+ onClick={(e) => {
+ e.stopPropagation();
+ onInstall();
+ }}
+ title={t(installed ? 'mcp.installed' : 'mcp.install')}
+ >
+ {installed ? <Check /> : <Download />}
+ </Button>
+ </div>
+ </ItemActions>
+ </Item>
+ );
+}
+
+interface HubPanelProps {
+ hubId: string;
+ hub?: HubInfo;
+ installedNames: Set<string>;
+ onInstalled: () => void;
+}
+
+function HubPanel({ hubId, hub, installedNames, onInstalled }: HubPanelProps) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState('');
+ const [installing, setInstalling] = useState<MCPCard | null>(null);
+ // Read once per mount: reading the clock during render is impure, and
+ // a browse session is far shorter than the units this rounds to.
+ const [now] = useState(() => Date.now() / 1000);
+ // The list already carries everything the drawer shows, but the detail
+ // endpoint is where a hub may fill in more.
+ const drawer = useResourceDrawer(
+ useCallback((card) => hubApi.mcp.getCard(card.hub_id as string, (card as MCPCard).id), []),
+ );
+ const { cards, loading, loadingMore, error, hasMore, loadMore, refetch } = useMCPHubCards(
+ hubId,
+ query,
+ );
+
+ return (
+ // Falls back to the raw id while the hub list is still loading.
+ <ResourcePanel
+ title={hub?.display_name ?? hubId}
+ description={hub?.description}
+ icon={
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={hub?.icon_url ?? undefined}
+ alt={hub?.display_name ?? hubId}
+ />
+ <AvatarFallback className="rounded-md">
+ {(hub?.display_name ?? hubId).slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ }
+ search={{
+ value: query,
+ onChange: setQuery,
+ placeholder: t('mcp.searchPlaceholder'),
+ }}
+ >
+ <div className="flex flex-col gap-y-4">
+ {loading ? (
+ <div className="flex justify-center py-10">
+ <Spinner />
+ </div>
+ ) : error ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <TriangleAlert />
+ </EmptyMedia>
+ <EmptyTitle>{t('mcp.loadFailedTitle')}</EmptyTitle>
+ <EmptyDescription>{t('mcp.loadFailedDescription')}</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="sm" onClick={refetch}>
+ {t('mcp.retry')}
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : cards.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Blocks />
+ </EmptyMedia>
+ <EmptyTitle>{t('mcp.noCardsTitle')}</EmptyTitle>
+ <EmptyDescription>{t('mcp.noCardsDescription')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <ItemGroup className="gap-0">
+ {/* gap-0: the separators carry the spacing, so rows do
+ not drift apart from the line between them. */}
+ {cards.map((card, index) => (
+ <Fragment key={`${card.hub_id}:${card.id}`}>
+ {index > 0 && <ItemSeparator />}
+ <CardItem
+ card={card}
+ installed={installedNames.has(card.name)}
+ now={now}
+ onInstall={() => setInstalling(card)}
+ onOpen={() => drawer.open(card)}
+ />
+ </Fragment>
+ ))}
+ </ItemGroup>
+ )}
+
+ {/* Cursor pagination — no page numbers and no total to show. */}
+ {hasMore && (
+ <LoadMore shown={cards.length} loading={loadingMore} onLoad={loadMore} />
+ )}
+ </div>
+
+ <ResourceDetailDrawer
+ skill={drawer.opened}
+ loading={drawer.loading}
+ onOpenChange={(open) => {
+ if (!open) drawer.close();
+ }}
+ body={<MCPDetailBody card={drawer.opened as MCPCard | null} />}
+ action={
+ <Button
+ disabled={drawer.opened !== null && installedNames.has(drawer.opened.name)}
+ onClick={() => {
+ // One overlay at a time: the install form replaces
+ // the drawer rather than stacking on top of it.
+ setInstalling(drawer.opened as MCPCard);
+ drawer.close();
+ }}
+ >
+ {drawer.opened && installedNames.has(drawer.opened.name) ? (
+ <Check />
+ ) : (
+ <Download />
+ )}
+ {t(
+ drawer.opened && installedNames.has(drawer.opened.name)
+ ? 'mcp.installed'
+ : 'mcp.install',
+ )}
+ </Button>
+ }
+ />
+
+ <InstallMCPDialog
+ card={installing}
+ onOpenChange={(open) => {
+ if (!open) setInstalling(null);
+ }}
+ onInstalled={onInstalled}
+ />
+ </ResourcePanel>
+ );
+}
+
+interface MinePanelProps {
+ mcps: MCPView[];
+ loading: boolean;
+ onEdit: (mcp: MCPView) => void;
+ onRemove: (mcpId: string) => void;
+}
+
+function MinePanel({ mcps, loading, onEdit, onRemove }: MinePanelProps) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState('');
+
+ // Filtered client-side: the library is the user's own and small, so a
+ // round trip per keystroke would buy nothing.
+ const needle = query.trim().toLowerCase();
+ const shown = needle
+ ? mcps.filter((mcp) =>
+ [mcp.name, mcp.display_name ?? '', mcp.description, ...mcp.tags].some((field) =>
+ field.toLowerCase().includes(needle),
+ ),
+ )
+ : mcps;
+
+ return (
+ <ResourcePanel
+ title={t('common.my-mcp')}
+ description={t('mcp.mineDescription')}
+ icon={<Store className="size-5 text-muted-foreground" />}
+ search={
+ // Hidden while there is nothing to search through.
+ mcps.length > 0
+ ? {
+ value: query,
+ onChange: setQuery,
+ placeholder: t('mcp.mineSearchPlaceholder'),
+ }
+ : undefined
+ }
+ >
+ {loading ? (
+ <div className="flex justify-center py-10">
+ <Spinner />
+ </div>
+ ) : mcps.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Store />
+ </EmptyMedia>
+ <EmptyTitle>{t('mcp.mineEmptyTitle')}</EmptyTitle>
+ <EmptyDescription>{t('mcp.mineEmptyDescription')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : shown.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Blocks />
+ </EmptyMedia>
+ <EmptyTitle>{t('mcp.noCardsTitle')}</EmptyTitle>
+ <EmptyDescription>{t('mcp.noCardsDescription')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <ItemGroup className="gap-0">
+ {shown.map((mcp, index) => (
+ <>
+ {index > 0 && <ItemSeparator />}
+ <Item key={mcp.id}>
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={mcp.icon_url ?? undefined}
+ alt={mcp.display_name || mcp.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {(mcp.display_name || mcp.name)
+ .slice(0, 1)
+ .toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+
+ <ItemContent>
+ <ItemTitle>
+ <span className="font-medium">
+ {mcp.display_name || mcp.name}
+ </span>
+ {mcp.author && (
+ <span className="text-xs text-muted-foreground">
+ @{mcp.author}
+ </span>
+ )}
+ {mcp.is_stateful && (
+ <span
+ key={'state'}
+ className="text-xs text-muted-foreground/60"
+ >
+ #{t('mcp.stateful')}
+ </span>
+ )}
+ {mcp.tags.slice(0, 4).map((tag) => (
+ <span
+ key={tag}
+ className="text-xs text-muted-foreground/60"
+ >
+ #{tag}
+ </span>
+ ))}
+ </ItemTitle>
+ <ItemDescription className="line-clamp-1">
+ {mcp.description}
+ </ItemDescription>
+ </ItemContent>
+
+ <ItemActions className="gap-1">
+ {mcp.version && (
+ <span className="text-xs text-muted-foreground whitespace-nowrap">
+ {mcp.version}
+ </span>
+ )}
+ {mcp.hub_id && mcp.card_id && (
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={() => onEdit(mcp)}
+ title={t('common.edit')}
+ >
+ <Pencil />
+ </Button>
+ )}
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={() => onRemove(mcp.id)}
+ title={t('common.delete')}
+ >
+ <Trash2 />
+ </Button>
+ </ItemActions>
+ </Item>
+ </>
+ ))}
+ </ItemGroup>
+ )}
+ </ResourcePanel>
+ );
+}
+
+export function MCPHubPage() {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ // No `hubId` in the URL means the "mine" tab, which is the default.
+ const { hubId } = useParams<{ hubId?: string }>();
+ const { hubs, loading: hubsLoading, error: hubsError, refetch } = useMCPHubs();
+ // Loaded page-wide, not per panel: the hub view needs it to mark cards
+ // as already installed, and the "mine" view to list them.
+ const { mcps, loading: mcpsLoading, refetch: refetchMcps, remove } = useMCPs();
+ const installedNames = new Set(mcps.map((mcp) => mcp.name));
+ // Editing re-opens the install form against the originating card, so
+ // the card has to be fetched before the dialog can render its inputs.
+ const [editing, setEditing] = useState<MCPView | null>(null);
+ const [editingCard, setEditingCard] = useState<MCPCard | null>(null);
+
+ useEffect(() => {
+ if (!editing?.hub_id || !editing.card_id) return;
+ let current = true;
+ hubApi.mcp
+ .getCard(editing.hub_id, editing.card_id)
+ .then((card) => {
+ if (current) setEditingCard(card);
+ })
+ .catch(() => {
+ // The hub is gone or the card was dropped; the dialog stays
+ // shut and the toast from the client says why.
+ if (current) setEditing(null);
+ });
+ return () => {
+ current = false;
+ };
+ }, [editing]);
+
+ return (
+ <div className="flex size-full">
+ <Sidebar collapsible="none" className="border-r">
+ <SidebarHeader className="flex flex-col mt-5 gap-y-1">
+ <div className="text-lg font-semibold">{t('common.mcp-hub')}</div>
+ <div className="text-muted-foreground text-xs">{t('mcp.subtitle')}</div>
+ </SidebarHeader>
+ <SidebarContent className="my-5">
+ <SidebarGroup>
+ <SidebarGroupLabel>{t('common.mine')}</SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ isActive={!hubId}
+ onClick={() => navigate('/mcp')}
+ >
+ <Store />
+ <span className="truncate">{t('common.my-mcp')}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+
+ <SidebarGroup>
+ <SidebarGroupLabel>{t('mcp.hubsLabel')}</SidebarGroupLabel>
+ <SidebarGroupContent>
+ {hubsLoading ? (
+ <div className="flex justify-center py-4">
+ <Spinner />
+ </div>
+ ) : hubsError ? (
+ // Distinct from the empty state on purpose: a
+ // failed request otherwise reads as "no hubs
+ // configured", pointing at the wrong problem.
+ <Empty className="border-none py-4 min-h-40">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <TriangleAlert />
+ </EmptyMedia>
+ <EmptyTitle>{t('mcp.loadFailedTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('mcp.loadFailedDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="sm" onClick={refetch}>
+ {t('mcp.retry')}
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : hubs.length === 0 ? (
+ <Empty className="border-none py-4 min-h-40">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Blocks />
+ </EmptyMedia>
+ <EmptyTitle>{t('mcp.noHubsTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('mcp.noHubsDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <SidebarMenu>
+ {hubs.map((hub) => (
+ <SidebarMenuItem key={hub.hub_id}>
+ <SidebarMenuButton
+ isActive={hubId === hub.hub_id}
+ onClick={() => navigate(`/mcp/${hub.hub_id}`)}
+ title={hub.description}
+ >
+ <Avatar className="size-4 rounded-sm">
+ <AvatarImage
+ src={hub.icon_url ?? undefined}
+ alt={hub.display_name}
+ />
+ <AvatarFallback className="rounded-sm text-[10px]">
+ {hub.display_name.slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <span className="truncate">{hub.display_name}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ))}
+ </SidebarMenu>
+ )}
+ </SidebarGroupContent>
+ </SidebarGroup>
+ </SidebarContent>
+ </Sidebar>
+
+ <main className="flex-1 min-w-0 min-h-0 overflow-hidden">
+ {hubId ? (
+ // Remount on hub change so the panel's query box resets.
+ <HubPanel
+ key={hubId}
+ hubId={hubId}
+ hub={hubs.find((h) => h.hub_id === hubId)}
+ installedNames={installedNames}
+ onInstalled={refetchMcps}
+ />
+ ) : (
+ <MinePanel
+ mcps={mcps}
+ loading={mcpsLoading}
+ onEdit={setEditing}
+ onRemove={remove}
+ />
+ )}
+ </main>
+
+ <InstallMCPDialog
+ card={editing ? editingCard : null}
+ editing={editing}
+ onOpenChange={(open) => {
+ if (!open) {
+ setEditing(null);
+ setEditingCard(null);
+ }
+ }}
+ onInstalled={refetchMcps}
+ />
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/skill/index.tsx b/examples/web_ui/frontend/src/pages/skill/index.tsx
new file mode 100644
index 000000000..624524ea6
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/skill/index.tsx
@@ -0,0 +1,574 @@
+import { Blocks, BookMarked, Check, Download, Trash2, TriangleAlert } from 'lucide-react';
+import { Fragment, useCallback, useState } from 'react';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import type { HubInfo, SkillCard, SkillView } from '@/api';
+import { hubApi, skillApi } from '@/api';
+import { ApiError } from '@/api/client';
+import { ResourceDetailDrawer } from '@/components/drawer/ResourceDetailDrawer.tsx';
+import { LoadMore } from '@/components/hub/LoadMore.tsx';
+import { ResourcePanel } from '@/components/hub/ResourcePanel.tsx';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty.tsx';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemSeparator,
+ ItemTitle,
+} from '@/components/ui/item.tsx';
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarGroup,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarMenu,
+ SidebarMenuButton,
+ SidebarMenuItem,
+} from '@/components/ui/sidebar.tsx';
+import { Spinner } from '@/components/ui/spinner.tsx';
+import { useResourceDrawer } from '@/hooks/useResourceDrawer.ts';
+import { useSkillHubCards } from '@/hooks/useSkillHubCards.ts';
+import { useSkillHubs } from '@/hooks/useSkillHubs.ts';
+import { useSkills } from '@/hooks/useSkills.ts';
+import { useTranslation } from '@/i18n/useI18n';
+import { formatTime } from '@/utils/common';
+
+interface CardItemProps {
+ card: SkillCard;
+ installed: boolean;
+ installing: boolean;
+ /** "Now" in epoch seconds, pinned by the panel so every row in a
+ * render agrees and the age does not shift on unrelated re-renders. */
+ now: number;
+ onInstall: () => void;
+ onOpen: () => void;
+}
+
+function CardItem({ card, installed, installing, now, onInstall, onOpen }: CardItemProps) {
+ const { t } = useTranslation();
+
+ return (
+ <Item className="cursor-pointer hover:bg-accent/50" onClick={onOpen}>
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={card.icon_url ?? undefined}
+ alt={card.display_name || card.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {(card.display_name || card.name).slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+
+ <ItemContent>
+ {/* Name, author, tags — each step lighter than the last, so
+ the eye lands on the name first. */}
+ <ItemTitle>
+ <span className="font-medium">{card.display_name || card.name}</span>
+ {card.author && (
+ <span className="text-xs text-muted-foreground">@{card.author}</span>
+ )}
+ {card.tags.slice(0, 4).map((tag) => (
+ <span key={tag} className="text-xs text-muted-foreground/60">
+ #{tag}
+ </span>
+ ))}
+ </ItemTitle>
+ <ItemDescription className="line-clamp-1">{card.description}</ItemDescription>
+ </ItemContent>
+
+ <ItemActions className="flex-col items-end">
+ {/* Rendered even when empty: a missing timestamp would
+ otherwise drop this row and slide the counter up, so
+ rows would not line up with each other. */}
+ <span className="h-4 text-xs text-muted-foreground whitespace-nowrap">
+ {/* updated_at is in seconds, as is formatTime. */}
+ {card.updated_at
+ ? now - card.updated_at < 3600
+ ? t('skill.updatedRecently')
+ : t('skill.updatedAgo', {
+ ago: formatTime(now - card.updated_at, {
+ leadingUnitOnly: true,
+ }),
+ })
+ : null}
+ </span>
+ <div className="flex h-8 items-center gap-2">
+ {/* Explicit null check: a hub reporting 0 downloads is
+ saying something, one that does not count them is not. */}
+ {card.downloads != null && (
+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
+ <Download className="size-3" />
+ {card.downloads.toLocaleString()}
+ </span>
+ )}
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ disabled={installed || installing}
+ // Installing straight from the row must not also
+ // open the drawer behind it.
+ onClick={(e) => {
+ e.stopPropagation();
+ onInstall();
+ }}
+ title={t(installed ? 'skill.installed' : 'skill.install')}
+ >
+ {installing ? <Spinner /> : installed ? <Check /> : <Download />}
+ </Button>
+ </div>
+ </ItemActions>
+ </Item>
+ );
+}
+
+interface HubPanelProps {
+ hubId: string;
+ hub?: HubInfo;
+ installedNames: Set<string>;
+ onInstalled: () => void;
+}
+
+function HubPanel({ hubId, hub, installedNames, onInstalled }: HubPanelProps) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState('');
+ const [installingId, setInstallingId] = useState<string | null>(null);
+ const drawer = useResourceDrawer(
+ useCallback(
+ (skill) => hubApi.skill.getCard(skill.hub_id as string, (skill as SkillCard).id),
+ [],
+ ),
+ );
+ // Read once per mount: reading the clock during render is impure, and
+ // a browse session is far shorter than the units this rounds to.
+ const [now] = useState(() => Date.now() / 1000);
+ const { cards, loading, loadingMore, error, hasMore, loadMore, refetch } = useSkillHubCards(
+ hubId,
+ query,
+ );
+
+ // A skill needs no configuration, so there is nothing to ask for —
+ // unlike an MCP install, this goes straight through without a dialog.
+ const handleInstall = async (card: SkillCard) => {
+ setInstallingId(card.id);
+ try {
+ await hubApi.skill.install(card.hub_id, card.id);
+ onInstalled();
+ } catch (e) {
+ // A 409 already surfaced as a toast from the client.
+ if (!(e instanceof ApiError)) throw e;
+ } finally {
+ setInstallingId(null);
+ }
+ };
+
+ return (
+ // Falls back to the raw id while the hub list is still loading.
+ <ResourcePanel
+ title={hub?.display_name ?? hubId}
+ description={hub?.description}
+ icon={
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={hub?.icon_url ?? undefined}
+ alt={hub?.display_name ?? hubId}
+ />
+ <AvatarFallback className="rounded-md">
+ {(hub?.display_name ?? hubId).slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ }
+ search={{
+ value: query,
+ onChange: setQuery,
+ placeholder: t('skill.searchPlaceholder'),
+ }}
+ >
+ <div className="flex flex-col gap-y-4">
+ {loading ? (
+ <div className="flex justify-center py-10">
+ <Spinner />
+ </div>
+ ) : error ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <TriangleAlert />
+ </EmptyMedia>
+ <EmptyTitle>{t('skill.loadFailedTitle')}</EmptyTitle>
+ <EmptyDescription>{t('skill.loadFailedDescription')}</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="sm" onClick={refetch}>
+ {t('skill.retry')}
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : cards.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Blocks />
+ </EmptyMedia>
+ <EmptyTitle>{t('skill.noCardsTitle')}</EmptyTitle>
+ <EmptyDescription>{t('skill.noCardsDescription')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <ItemGroup className="gap-0">
+ {/* gap-0: the separators carry the spacing, so rows do
+ not drift apart from the line between them. */}
+ {cards.map((card, index) => (
+ <Fragment key={`${card.hub_id}:${card.id}`}>
+ {index > 0 && <ItemSeparator />}
+ <CardItem
+ card={card}
+ installed={installedNames.has(card.name)}
+ installing={installingId === card.id}
+ now={now}
+ onInstall={() => handleInstall(card)}
+ onOpen={() => drawer.open(card)}
+ />
+ </Fragment>
+ ))}
+ </ItemGroup>
+ )}
+
+ {/* Cursor pagination — no page numbers and no total to show. */}
+ {hasMore && (
+ <LoadMore shown={cards.length} loading={loadingMore} onLoad={loadMore} />
+ )}
+ </div>
+
+ <ResourceDetailDrawer
+ skill={drawer.opened}
+ loading={drawer.loading}
+ onOpenChange={(open) => {
+ if (!open) drawer.close();
+ }}
+ action={
+ <Button
+ disabled={
+ drawer.opened !== null &&
+ (installedNames.has(drawer.opened.name) ||
+ installingId === (drawer.opened as SkillCard).id)
+ }
+ onClick={() => drawer.opened && handleInstall(drawer.opened as SkillCard)}
+ >
+ {drawer.opened && installedNames.has(drawer.opened.name) ? (
+ <Check />
+ ) : (
+ <Download />
+ )}
+ {t(
+ drawer.opened && installedNames.has(drawer.opened.name)
+ ? 'skill.installed'
+ : 'skill.install',
+ )}
+ </Button>
+ }
+ />
+ </ResourcePanel>
+ );
+}
+
+interface MinePanelProps {
+ skills: SkillView[];
+ loading: boolean;
+ onRemove: (skillId: string) => void;
+}
+
+function MinePanel({ skills, loading, onRemove }: MinePanelProps) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState('');
+ // The list view omits SKILL.md; the detail endpoint carries it.
+ const drawer = useResourceDrawer(
+ useCallback((skill) => skillApi.get((skill as SkillView).id), []),
+ );
+
+ // Filtered client-side: the library is the user's own and small, so a
+ // round trip per keystroke would buy nothing.
+ const needle = query.trim().toLowerCase();
+ const shown = needle
+ ? skills.filter((skill) =>
+ [skill.name, skill.display_name ?? '', skill.description, ...skill.tags].some(
+ (field) => field.toLowerCase().includes(needle),
+ ),
+ )
+ : skills;
+
+ return (
+ <ResourcePanel
+ title={t('common.my-skill')}
+ description={t('skill.mineDescription')}
+ icon={<BookMarked className="size-5 text-muted-foreground" />}
+ search={
+ // Hidden while there is nothing to search through.
+ skills.length > 0
+ ? {
+ value: query,
+ onChange: setQuery,
+ placeholder: t('skill.mineSearchPlaceholder'),
+ }
+ : undefined
+ }
+ >
+ {loading ? (
+ <div className="flex justify-center py-10">
+ <Spinner />
+ </div>
+ ) : skills.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <BookMarked />
+ </EmptyMedia>
+ <EmptyTitle>{t('skill.mineEmptyTitle')}</EmptyTitle>
+ <EmptyDescription>{t('skill.mineEmptyDescription')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : shown.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Blocks />
+ </EmptyMedia>
+ <EmptyTitle>{t('skill.noCardsTitle')}</EmptyTitle>
+ <EmptyDescription>{t('skill.noCardsDescription')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <ItemGroup className="gap-0">
+ {shown.map((skill, index) => (
+ <Fragment key={skill.id}>
+ {index > 0 && <ItemSeparator />}
+ <Item
+ className="cursor-pointer hover:bg-accent/50"
+ onClick={() => drawer.open(skill)}
+ >
+ <ItemMedia>
+ <Avatar className="rounded-md">
+ <AvatarImage
+ src={skill.icon_url ?? undefined}
+ alt={skill.display_name || skill.name}
+ loading="lazy"
+ />
+ <AvatarFallback className="rounded-md">
+ {(skill.display_name || skill.name)
+ .slice(0, 1)
+ .toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </ItemMedia>
+
+ <ItemContent>
+ <ItemTitle>
+ <span className="font-medium">
+ {skill.display_name || skill.name}
+ </span>
+ {/* A hand-added skill has no hub to name. */}
+ {skill.hub_id && (
+ <span className="text-xs text-muted-foreground">
+ @{skill.hub_id}
+ </span>
+ )}
+ {skill.tags.slice(0, 4).map((tag) => (
+ <span
+ key={tag}
+ className="text-xs text-muted-foreground/60"
+ >
+ #{tag}
+ </span>
+ ))}
+ </ItemTitle>
+ <ItemDescription className="line-clamp-1">
+ {skill.description}
+ </ItemDescription>
+ </ItemContent>
+
+ <ItemActions>
+ {skill.version && (
+ <span className="text-xs text-muted-foreground whitespace-nowrap">
+ {skill.version}
+ </span>
+ )}
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ // Deleting from the row must not also
+ // open the drawer behind it.
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemove(skill.id);
+ }}
+ title={t('common.delete')}
+ >
+ <Trash2 />
+ </Button>
+ </ItemActions>
+ </Item>
+ </Fragment>
+ ))}
+ </ItemGroup>
+ )}
+
+ <ResourceDetailDrawer
+ skill={drawer.opened}
+ loading={drawer.loading}
+ onOpenChange={(open) => {
+ if (!open) drawer.close();
+ }}
+ action={
+ <Button
+ variant="destructive"
+ onClick={() => {
+ if (drawer.opened) onRemove((drawer.opened as SkillView).id);
+ drawer.close();
+ }}
+ >
+ <Trash2 />
+ {t('common.delete')}
+ </Button>
+ }
+ />
+ </ResourcePanel>
+ );
+}
+
+export function SkillHubPage() {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ // No `hubId` in the URL means the "mine" tab, which is the default.
+ const { hubId } = useParams<{ hubId?: string }>();
+ const { hubs, loading: hubsLoading, error: hubsError, refetch } = useSkillHubs();
+ // Loaded page-wide, not per panel: the hub view needs it to mark cards
+ // as already installed, and the "mine" view to list them.
+ const { skills, loading: skillsLoading, refetch: refetchSkills, remove } = useSkills();
+ const installedNames = new Set(skills.map((skill) => skill.name));
+
+ return (
+ <div className="flex size-full">
+ <Sidebar collapsible="none" className="border-r">
+ <SidebarHeader className="flex flex-col mt-5 gap-y-1">
+ <div className="text-lg font-semibold">{t('common.skill-hub')}</div>
+ <div className="text-muted-foreground text-xs">{t('skill.subtitle')}</div>
+ </SidebarHeader>
+ <SidebarContent className="my-5">
+ <SidebarGroup>
+ <SidebarGroupLabel>{t('common.mine')}</SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ isActive={!hubId}
+ onClick={() => navigate('/skill')}
+ >
+ <BookMarked />
+ <span className="truncate">{t('common.my-skill')}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+
+ <SidebarGroup>
+ <SidebarGroupLabel>{t('skill.hubsLabel')}</SidebarGroupLabel>
+ <SidebarGroupContent>
+ {hubsLoading ? (
+ <div className="flex justify-center py-4">
+ <Spinner />
+ </div>
+ ) : hubsError ? (
+ // Distinct from the empty state on purpose: a
+ // failed request otherwise reads as "no hubs
+ // configured", pointing at the wrong problem.
+ <Empty className="border-none py-4 min-h-40">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <TriangleAlert />
+ </EmptyMedia>
+ <EmptyTitle>{t('skill.loadFailedTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('skill.loadFailedDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="sm" onClick={refetch}>
+ {t('skill.retry')}
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : hubs.length === 0 ? (
+ <Empty className="border-none py-4 min-h-40">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Blocks />
+ </EmptyMedia>
+ <EmptyTitle>{t('skill.noHubsTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('skill.noHubsDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <SidebarMenu>
+ {hubs.map((hub) => (
+ <SidebarMenuItem key={hub.hub_id}>
+ <SidebarMenuButton
+ isActive={hubId === hub.hub_id}
+ onClick={() => navigate(`/skill/${hub.hub_id}`)}
+ title={hub.description}
+ >
+ <Avatar className="size-4 rounded-sm">
+ <AvatarImage
+ src={hub.icon_url ?? undefined}
+ alt={hub.display_name}
+ />
+ <AvatarFallback className="rounded-sm text-[10px]">
+ {hub.display_name.slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <span className="truncate">{hub.display_name}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ))}
+ </SidebarMenu>
+ )}
+ </SidebarGroupContent>
+ </SidebarGroup>
+ </SidebarContent>
+ </Sidebar>
+
+ <main className="flex-1 min-w-0 min-h-0 overflow-hidden">
+ {hubId ? (
+ // Remount on hub change so the panel's query box resets.
+ <HubPanel
+ key={hubId}
+ hubId={hubId}
+ hub={hubs.find((h) => h.hub_id === hubId)}
+ installedNames={installedNames}
+ onInstalled={refetchSkills}
+ />
+ ) : (
+ <MinePanel skills={skills} loading={skillsLoading} onRemove={remove} />
+ )}
+ </main>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/utils/common.ts b/examples/web_ui/frontend/src/utils/common.ts
index 5ad509ae7..00671afcb 100644
--- a/examples/web_ui/frontend/src/utils/common.ts
+++ b/examples/web_ui/frontend/src/utils/common.ts
@@ -78,11 +78,21 @@ export const formatDuration = (seconds: number): number => {
* - Once the leading unit is hours, only whole hours are shown — minute and
* second precision is not useful at that scale and would only widen the
* badge when, e.g., a tool call sits awaiting user confirmation for hours.
+ * - The same reasoning extends past a day: only the leading whole unit is
+ * shown, up to years. Months and years use average lengths, so they are
+ * approximate by construction — fine for "updated 3mo ago", wrong for
+ * anything that needs calendar accuracy.
*
* @param seconds - The duration in seconds to format
- * @returns Formatted string (e.g., "45s", "2min30s", "3h")
+ * @param options.leadingUnitOnly - Drop the trailing seconds from the
+ * minutes case, so `49m33s` reads `49m`. Defaults to `false`, keeping the
+ * two-segment form the elapsed-time badges rely on.
+ * @returns Formatted string (e.g., "45s", "2min30s", "3h", "5d", "2y")
*/
-export const formatTime = (seconds: number): string => {
+export const formatTime = (
+ seconds: number,
+ options: { leadingUnitOnly?: boolean } = {},
+): string => {
const total = Math.floor(seconds);
if (total < 60) {
return `${total}s`;
@@ -90,7 +100,21 @@ export const formatTime = (seconds: number): string => {
if (total < 3600) {
const minutes = Math.floor(total / 60);
const remaining = total % 60;
- return remaining === 0 ? `${minutes}m` : `${minutes}m${remaining}s`;
+ if (options.leadingUnitOnly || remaining === 0) {
+ return `${minutes}m`;
+ }
+ return `${minutes}m${remaining}s`;
+ }
+ if (total < 86400) {
+ return `${Math.floor(total / 3600)}h`;
+ }
+ // 30.44 and 365.25 days — the average month and year, so a "1y" does
+ // not flip back to "12mo" for the leap-day stragglers.
+ if (total < 2629746) {
+ return `${Math.floor(total / 86400)}d`;
+ }
+ if (total < 31556952) {
+ return `${Math.floor(total / 2629746)}mo`;
}
- return `${Math.floor(total / 3600)}h`;
+ return `${Math.floor(total / 31556952)}y`;
};
diff --git a/src/agentscope/_utils/_common.py b/src/agentscope/_utils/_common.py
index cd27c9da8..a6207f54d 100644
--- a/src/agentscope/_utils/_common.py
+++ b/src/agentscope/_utils/_common.py
@@ -365,3 +365,25 @@ def _estimate_bytes(tokens: int) -> int:
"""Estimate the number of bytes with given tokens."""
return int(tokens * 4)
+
+
+def _describe_exception(error: BaseException) -> str:
+ """Render an exception as something a person can act on.
+
+ Async transports run inside task groups, so what surfaces is often
+ an ``ExceptionGroup`` whose own message is ``"unhandled errors in a
+ TaskGroup (1 sub-exception)"`` — true, and of no use to anyone. The
+ real cause is a leaf, so leaves are what get reported.
+
+ Args:
+ error (`BaseException`):
+ The exception to describe.
+
+ Returns:
+ `str`:
+ The leaf causes, joined; the exception type when a leaf
+ carries no message of its own.
+ """
+ if isinstance(error, BaseExceptionGroup):
+ return "; ".join(_describe_exception(sub) for sub in error.exceptions)
+ return str(error) or type(error).__name__
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.py
index 255b2c984..933c54ecf 100644
--- a/src/agentscope/app/_app.py
+++ b/src/agentscope/app/_app.py
@@ -4,6 +4,7 @@ from typing import Type, TYPE_CHECKING, Any
from ._lifespan import lifespan
from .access import DenyAllResourceAccessPolicy, ResourceAccessPolicyBase
+from .hub import HubBase, HubError, MCPHubBase, SkillHubBase
from .rag.blob_store import BlobStoreBase, LocalBlobStore
from .rag.knowledge_base_manager import KnowledgeBaseManagerBase
from .workspace_manager import WorkspaceManagerBase
@@ -11,11 +12,14 @@ from ._router import (
agent_router,
chat_router,
credential_router,
+ hub_router,
knowledge_base_router,
+ mcp_router,
model_router,
tts_model_router,
schedule_router,
session_router,
+ skill_router,
workspace_router,
)
from ._types import AgentMiddlewareFactory, AgentToolFactory, SubAgentTemplate
@@ -40,6 +44,35 @@ else:
FastAPIMiddleware = Any
+def _index_hubs(hubs: list | None, kind: str) -> dict:
+ """Key the hubs by id, rejecting duplicates.
+
+ Args:
+ hubs (`list | None`):
+ The hubs passed to :func:`create_app`.
+ kind (`str`):
+ The hub kind, used in the error message.
+
+ Returns:
+ `dict`:
+ The hubs keyed by :attr:`HubBase.hub_id`.
+
+ Raises:
+ `ValueError`:
+ When two hubs of the same kind share an id, which would make
+ them indistinguishable in the routes.
+ """
+ indexed: dict[str, HubBase] = {}
+ for hub in hubs or []:
+ if hub.hub_id in indexed:
+ raise ValueError(
+ f"Duplicate {kind} hub id {hub.hub_id!r}: hub ids must be "
+ f"unique so routes address exactly one hub.",
+ )
+ indexed[hub.hub_id] = hub
+ return indexed
+
+
def create_app(
storage: StorageBase,
message_bus: MessageBus,
@@ -49,6 +82,8 @@ def create_app(
knowledge_chunker: ChunkerBase | None = None,
blob_store: BlobStoreBase | None = None,
enable_index_worker: bool = True,
+ mcp_hubs: list[MCPHubBase] | None = None,
+ skill_hubs: list[SkillHubBase] | None = None,
*,
extra_credentials: list[Type[CredentialBase]] | None = None,
extra_middlewares: list[FastAPIMiddleware] | None = None,
@@ -143,6 +178,10 @@ def create_app(
process is expected to consume tasks from the message
bus. No effect when ``knowledge_base_manager`` is
``None``.
+ mcp_hubs (`list[MCPHubBase] | None`, optional):
+ The MCP hubs that provide MCPs.
+ skill_hubs (`list[SkillHubBase] | None`, optional):
+ The SkillHubs that provide skills.
extra_credentials (`list[Type[CredentialBase]] | None`, optional):
Additional :class:`~agentscope.credential.CredentialBase`
subclasses to register before the app starts. Equivalent to
@@ -194,7 +233,8 @@ def create_app(
Returns:
`FastAPI`: A fully configured application ready to serve requests.
"""
- from fastapi import FastAPI
+ from fastapi import FastAPI, Request, status
+ from fastapi.responses import JSONResponse
# Register any user-supplied credential types before the app starts
for cls in extra_credentials or []:
@@ -213,6 +253,8 @@ def create_app(
app.state.resource_access_policy = (
resource_access_policy or DenyAllResourceAccessPolicy()
)
+ app.state.mcp_hubs = _index_hubs(mcp_hubs, "MCP")
+ app.state.skill_hubs = _index_hubs(skill_hubs, "skill")
# Parser / chunker / blob-store defaults only make sense when the
# KB feature is actually enabled. When ``knowledge_base_manager`` is
@@ -258,15 +300,36 @@ def create_app(
agent_router,
chat_router,
credential_router,
+ hub_router,
knowledge_base_router,
+ mcp_router,
schedule_router,
session_router,
+ skill_router,
workspace_router,
model_router,
tts_model_router,
):
app.include_router(router)
+ @app.exception_handler(HubError)
+ async def _on_hub_error(_: Request, exc: HubError) -> JSONResponse:
+ """Report an upstream registry failure as a gateway error.
+
+ A hub is a third party we proxy, so its 429 or 500 is not this
+ service's fault and must not read as one — a 500 here would send
+ the user hunting for a bug on our side.
+ """
+ status_code = (
+ status.HTTP_503_SERVICE_UNAVAILABLE
+ if exc.status_code == 429
+ else status.HTTP_502_BAD_GATEWAY
+ )
+ return JSONResponse(
+ status_code=status_code,
+ content={"detail": str(exc)},
+ )
+
# Optional extra middlewares
for middleware in extra_middlewares or []:
app.add_middleware(middleware.cls, **middleware.kwargs)
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.py
index 5e4c14819..e7bc595a3 100644
--- a/src/agentscope/app/_lifespan.py
+++ b/src/agentscope/app/_lifespan.py
@@ -60,6 +60,14 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
if blob_store is not None:
await stack.enter_async_context(blob_store)
+ # Hubs live as long as the process so each can hold one client
+ # to its registry, instead of re-handshaking per catalog page.
+ for hub in (
+ *app.state.mcp_hubs.values(),
+ *app.state.skill_hubs.values(),
+ ):
+ await stack.enter_async_context(hub)
+
bg_manager = await stack.enter_async_context(
BackgroundTaskManager(message_bus=message_bus),
)
diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.py
index 9f8ea4219..7df89a383 100644
--- a/src/agentscope/app/_router/__init__.py
+++ b/src/agentscope/app/_router/__init__.py
@@ -3,9 +3,12 @@
from ._agent import agent_router
from ._chat import chat_router
from ._credential import credential_router
+from ._hub import hub_router
from ._knowledge_base import knowledge_base_router
+from ._mcp import mcp_router
from ._schedule import schedule_router
from ._session import session_router
+from ._skill import skill_router
from ._model import model_router
from ._tts_model import tts_model_router
from ._workspace import workspace_router
@@ -16,8 +19,11 @@ __all__ = [
"tts_model_router",
"chat_router",
"credential_router",
+ "hub_router",
"knowledge_base_router",
+ "mcp_router",
"schedule_router",
"session_router",
+ "skill_router",
"workspace_router",
]
diff --git a/src/agentscope/app/_router/_hub.py b/src/agentscope/app/_router/_hub.py
new file mode 100644
index 000000000..4e8c8254c
--- /dev/null
+++ b/src/agentscope/app/_router/_hub.py
@@ -0,0 +1,308 @@
+# -*- coding: utf-8 -*-
+"""Hub router — browse resource hubs and install from them.
+
+The frontend flow is three levels deep: list the hubs, browse one hub's
+cards, then install a chosen card into the caller's library. Cards are
+never merged across hubs, which keeps ranking a per-hub concern.
+
+Installing is user-level for both kinds — nothing here touches a
+workspace. See ``_mcp.py`` / ``_skill.py`` for the libraries it writes.
+"""
+from typing import TypeVar
+
+from fastapi import APIRouter, Depends, HTTPException, Query, status
+
+from ..deps import (
+ get_current_user_id,
+ get_mcp_hubs,
+ get_skill_hubs,
+ get_storage,
+)
+from ..hub import (
+ HubBase,
+ MCPCard,
+ MCPHubBase,
+ MCPHubPage,
+ SkillCard,
+ SkillHubBase,
+ SkillHubPage,
+)
+from .._service import MCPRenderError, render_mcp
+from ..storage import MCPRecord, SkillRecord, StorageBase
+from ._schema import HubInfo, InstallMCPRequest, MCPView, SkillView
+
+hub_router = APIRouter(prefix="/hub", tags=["hub"])
+
+HubT = TypeVar("HubT", bound=HubBase)
+
+
+def _pick_hub(hubs: dict[str, HubT], hub_id: str) -> HubT:
+ """Return the hub under ``hub_id`` or raise 404.
+
+ Args:
+ hubs (`dict[str, HubT]`):
+ The registered hubs keyed by id.
+ hub_id (`str`):
+ The requested hub id.
+
+ Returns:
+ `HubT`:
+ The matching hub, keeping its concrete type.
+
+ Raises:
+ `HTTPException`:
+ ``404`` when no hub is registered under ``hub_id``.
+ """
+ hub = hubs.get(hub_id)
+ if hub is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Hub {hub_id!r} is not registered.",
+ )
+ return hub
+
+
+def _describe(hubs: dict) -> list[HubInfo]:
+ """Render the hub picker entries in a stable order.
+
+ Args:
+ hubs (`dict`):
+ The registered hubs keyed by id.
+
+ Returns:
+ `list[HubInfo]`:
+ One entry per hub, ordered by id.
+ """
+ return [
+ HubInfo(
+ hub_id=hub.hub_id,
+ display_name=hub.display_name,
+ description=hub.description,
+ icon_url=hub.icon_url,
+ )
+ for _, hub in sorted(hubs.items())
+ ]
+
+
+# ---------------------------------------------------------------------------
+# MCP hubs
+# ---------------------------------------------------------------------------
+
+
+@hub_router.get("/mcp")
+async def list_mcp_hubs(
+ hubs: dict[str, MCPHubBase] = Depends(get_mcp_hubs),
+) -> list[HubInfo]:
+ """Return every registered MCP hub."""
+ return _describe(hubs)
+
+
+@hub_router.get("/mcp/{hub_id}/cards")
+async def list_mcp_cards(
+ hub_id: str,
+ *,
+ q: str | None = Query(default=None),
+ cursor: str | None = Query(default=None),
+ limit: int = Query(default=20, ge=1, le=200),
+ user_id: str = Depends(get_current_user_id),
+ hubs: dict[str, MCPHubBase] = Depends(get_mcp_hubs),
+) -> MCPHubPage:
+ """Browse or search one MCP hub's catalog."""
+ hub = _pick_hub(hubs, hub_id)
+ return await hub.list_mcps(user_id, q=q, cursor=cursor, limit=limit)
+
+
+@hub_router.get("/mcp/{hub_id}/cards/{card_id}")
+async def get_mcp_card(
+ hub_id: str,
+ card_id: str,
+ *,
+ user_id: str = Depends(get_current_user_id),
+ hubs: dict[str, MCPHubBase] = Depends(get_mcp_hubs),
+) -> MCPCard:
+ """Return one MCP card, including the inputs the user must fill."""
+ hub = _pick_hub(hubs, hub_id)
+ try:
+ return await hub.get_mcp(user_id, card_id)
+ except KeyError as e:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Hub {hub_id!r} has no MCP {card_id!r}.",
+ ) from e
+
+
+@hub_router.post(
+ "/mcp/{hub_id}/cards/{card_id}/install",
+ status_code=status.HTTP_201_CREATED,
+)
+async def install_mcp(
+ hub_id: str,
+ card_id: str,
+ body: InstallMCPRequest,
+ *,
+ user_id: str = Depends(get_current_user_id),
+ hubs: dict[str, MCPHubBase] = Depends(get_mcp_hubs),
+ storage: StorageBase = Depends(get_storage),
+) -> MCPView:
+ """Fill a card's template and add the result to the user's library.
+
+ Installing is a user-level act with no workspace involved — putting
+ the MCP into a session's workspace is separate and explicit. The
+ record keeps ``(hub_id, card_id)`` so the library can later answer
+ "where did this come from" and "is there a newer version".
+
+ Note that the config is not connection-tested here, so a mistyped
+ API key surfaces on first use rather than now. Testing it would mean
+ connecting from the app process, and a stdio MCP would then spawn
+ its command here instead of in the workspace sandbox.
+ """
+ hub = _pick_hub(hubs, hub_id)
+ try:
+ card = await hub.get_mcp(user_id, card_id)
+ except KeyError as e:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Hub {hub_id!r} has no MCP {card_id!r}.",
+ ) from e
+
+ try:
+ client = render_mcp(card, body.values, body.name)
+ except MCPRenderError as e:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=str(e),
+ ) from e
+
+ record = MCPRecord(
+ user_id=user_id,
+ client=client,
+ values=body.values,
+ display_name=card.display_name,
+ description=card.description,
+ tags=card.tags,
+ author=card.author,
+ icon_url=card.icon_url,
+ url=card.url,
+ hub_id=card.hub_id,
+ card_id=card.id,
+ version=card.version,
+ )
+ try:
+ await storage.upsert_mcp(user_id, record)
+ except ValueError as e:
+ # The name is unique per user, so a clash is the caller's to
+ # resolve by passing a different one.
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ f"{e} Pass a different 'name' to install it alongside "
+ f"the existing one."
+ ),
+ ) from e
+
+ return MCPView.from_record(record)
+
+
+# ---------------------------------------------------------------------------
+# Skill hubs
+# ---------------------------------------------------------------------------
+
+
+@hub_router.get("/skill")
+async def list_skill_hubs(
+ hubs: dict[str, SkillHubBase] = Depends(get_skill_hubs),
+) -> list[HubInfo]:
+ """Return every registered skill hub."""
+ return _describe(hubs)
+
+
+@hub_router.get("/skill/{hub_id}/cards")
+async def list_skill_cards(
+ hub_id: str,
+ *,
+ q: str | None = Query(default=None),
+ cursor: str | None = Query(default=None),
+ limit: int = Query(default=20, ge=1, le=200),
+ user_id: str = Depends(get_current_user_id),
+ hubs: dict[str, SkillHubBase] = Depends(get_skill_hubs),
+) -> SkillHubPage:
+ """Browse or search one skill hub's catalog."""
+ hub = _pick_hub(hubs, hub_id)
+ return await hub.list_skills(user_id, q=q, cursor=cursor, limit=limit)
+
+
+@hub_router.get("/skill/{hub_id}/cards/{card_id}")
+async def get_skill_card(
+ hub_id: str,
+ card_id: str,
+ *,
+ user_id: str = Depends(get_current_user_id),
+ hubs: dict[str, SkillHubBase] = Depends(get_skill_hubs),
+) -> SkillCard:
+ """Return one skill card, including its ``SKILL.md`` body."""
+ hub = _pick_hub(hubs, hub_id)
+ try:
+ return await hub.get_skill(user_id, card_id)
+ except KeyError as e:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Hub {hub_id!r} has no skill {card_id!r}.",
+ ) from e
+
+
+@hub_router.post(
+ "/skill/{hub_id}/cards/{card_id}/install",
+ status_code=status.HTTP_201_CREATED,
+)
+async def install_skill(
+ hub_id: str,
+ card_id: str,
+ *,
+ name: str | None = Query(default=None),
+ user_id: str = Depends(get_current_user_id),
+ hubs: dict[str, SkillHubBase] = Depends(get_skill_hubs),
+ storage: StorageBase = Depends(get_storage),
+) -> SkillView:
+ """Add a skill card to the user's library.
+
+ Mirrors the MCP install: user-level, no workspace involved. The
+ archive is not downloaded here — only the card's metadata is
+ recorded, and the files are fetched when the skill is actually put
+ into a workspace. So a hub that has since dropped the card fails
+ then rather than now.
+ """
+ hub = _pick_hub(hubs, hub_id)
+ try:
+ card = await hub.get_skill(user_id, card_id)
+ except KeyError as e:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Hub {hub_id!r} has no skill {card_id!r}.",
+ ) from e
+
+ record = SkillRecord(
+ user_id=user_id,
+ name=name or card.name,
+ display_name=card.display_name,
+ description=card.description,
+ tags=card.tags,
+ author=card.author,
+ icon_url=card.icon_url,
+ url=card.url,
+ markdown=card.markdown or "",
+ hub_id=card.hub_id,
+ card_id=card.id,
+ version=card.version,
+ )
+ try:
+ await storage.upsert_skill(user_id, record)
+ except ValueError as e:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ f"{e} Pass a different 'name' to install it alongside "
+ f"the existing one."
+ ),
+ ) from e
+
+ return SkillView.from_record(record)
diff --git a/src/agentscope/app/_router/_mcp.py b/src/agentscope/app/_router/_mcp.py
new file mode 100644
index 000000000..697db23f2
--- /dev/null
+++ b/src/agentscope/app/_router/_mcp.py
@@ -0,0 +1,126 @@
+# -*- coding: utf-8 -*-
+"""MCP router — the user's own library of installed MCPs.
+
+This is the user-level collection an install lands in, distinct from
+``/workspace/mcp``, which manages the MCPs of one session's workspace.
+Installing from a hub only writes here; putting an MCP into a workspace
+stays a separate, explicit act.
+"""
+from fastapi import APIRouter, Depends, HTTPException, status
+
+from ..deps import get_current_user_id, get_mcp_hubs, get_storage
+from ..hub import MCPHubBase
+from .._service import MCPRenderError, render_mcp
+from ..storage import StorageBase
+from ._schema import MCPView, UpdateMCPRequest
+
+mcp_router = APIRouter(prefix="/mcp", tags=["mcp"])
+
+
+@mcp_router.get("")
+async def list_mcps(
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+) -> list[MCPView]:
+ """Return every MCP the user has installed, ordered by name."""
+ records = await storage.list_mcps(user_id)
+ return sorted(
+ (MCPView.from_record(r) for r in records),
+ key=lambda view: view.name,
+ )
+
+
+@mcp_router.patch("/{mcp_id}")
+async def update_mcp(
+ mcp_id: str,
+ body: UpdateMCPRequest,
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+ hubs: dict[str, MCPHubBase] = Depends(get_mcp_hubs),
+) -> MCPView:
+ """Rename, enable/disable, or re-key an installed MCP.
+
+ Changing a secret is a re-render, not a field edit: an API key can
+ sit anywhere in the config — inside a URL, a header, an env var — so
+ the card's template plus the merged answers is the only thing that
+ knows where to put it.
+ """
+ record = await storage.get_mcp(user_id, mcp_id)
+ if record is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"No installed MCP with id {mcp_id!r}.",
+ )
+
+ if body.values is not None:
+ hub = hubs.get(record.hub_id or "")
+ if hub is None or record.card_id is None:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ "This MCP has no card to re-render from — its hub is "
+ "not registered, or it was added by hand."
+ ),
+ )
+ try:
+ card = await hub.get_mcp(user_id, record.card_id)
+ except KeyError as e:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=(
+ f"Hub {record.hub_id!r} no longer has the card this "
+ f"MCP was installed from."
+ ),
+ ) from e
+
+ # Merged, not replaced: the client sends only what changed, and
+ # a write-only field the form did not echo back must survive.
+ merged = {**record.values, **body.values}
+ try:
+ record.client = render_mcp(
+ card,
+ merged,
+ body.name or record.client.name,
+ )
+ except MCPRenderError as e:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=str(e),
+ ) from e
+ record.values = merged
+ record.version = card.version
+ elif body.name is not None:
+ record.client.name = body.name
+
+ if body.enabled is not None:
+ record.enabled = body.enabled
+
+ try:
+ await storage.upsert_mcp(user_id, record)
+ except ValueError as e:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=str(e),
+ ) from e
+
+ return MCPView.from_record(record)
+
+
+@mcp_router.delete("/{mcp_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_mcp(
+ mcp_id: str,
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+) -> None:
+ """Remove an MCP from the user's library.
+
+ Workspaces that already hold this MCP keep it — the workspace
+ relation is derived by name, not a foreign key, and tearing down a
+ live stateful MCP session as a side effect of a library edit would
+ surprise the user.
+ """
+ if not await storage.delete_mcp(user_id, mcp_id):
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"No installed MCP with id {mcp_id!r}.",
+ )
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index 8b08faa13..dc11f6bda 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -2,6 +2,17 @@
"""Schema models for the agent service."""
from ._chat import ChatRequest, ChatTriggerResponse
+from ._hub import HubInfo
+from ._hub_mcp import InstallMCPRequest, MCPView, UpdateMCPRequest
+from ._hub_skill import SkillView
+from ._workspace import (
+ AddFromLibraryRequest,
+ AddFromLibraryResponse,
+ AddSkillRequest,
+ AddSkillsFromLibraryRequest,
+ MCPClientStatus,
+ ToolInfo,
+)
from ._model import ListModelsResponse, ListModelsRequest
from ._tts_model import ListTTSModelsResponse, ListTTSModelsRequest
from ._schedule import (
@@ -57,6 +68,19 @@ from ._session import (
)
__all__ = [
+ # Hub
+ "HubInfo",
+ "InstallMCPRequest",
+ "MCPView",
+ "UpdateMCPRequest",
+ "SkillView",
+ # Workspace
+ "AddFromLibraryRequest",
+ "AddFromLibraryResponse",
+ "AddSkillRequest",
+ "AddSkillsFromLibraryRequest",
+ "MCPClientStatus",
+ "ToolInfo",
# Agent
"AgentSchemaResponse",
"AgentSchemaV2Response",
diff --git a/src/agentscope/app/_router/_schema/_hub.py b/src/agentscope/app/_router/_schema/_hub.py
new file mode 100644
index 000000000..b4ac6e338
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_hub.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+"""Hub schemas shared by the MCP and skill hub routes."""
+from pydantic import BaseModel, Field
+
+
+class HubInfo(BaseModel):
+ """One registered hub, as shown in the hub picker."""
+
+ hub_id: str = Field(description="The id addressing this hub.")
+ display_name: str = Field(description="The user-facing hub name.")
+ description: str = Field(description="The user-facing description.")
+ icon_url: str | None = Field(
+ default=None,
+ description="An image identifying the hub, when it has one.",
+ )
diff --git a/src/agentscope/app/_router/_schema/_hub_mcp.py b/src/agentscope/app/_router/_schema/_hub_mcp.py
new file mode 100644
index 000000000..d335d61af
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_hub_mcp.py
@@ -0,0 +1,127 @@
+# -*- coding: utf-8 -*-
+"""Schemas for installing and editing MCPs from a hub."""
+from pydantic import BaseModel, Field
+
+from ...storage import MCPRecord
+
+
+class InstallMCPRequest(BaseModel):
+ """The body of an MCP install call."""
+
+ name: str | None = Field(
+ default=None,
+ description=(
+ "The name to install under, defaulting to the card's name. "
+ "Must match ``[a-zA-Z0-9_-]+``; use it to resolve a clash "
+ "with an MCP already in the library."
+ ),
+ )
+ values: dict = Field(
+ default_factory=dict,
+ description=(
+ "The answers to the card's ``inputs_schema``, e.g. API keys."
+ ),
+ )
+
+
+class MCPView(BaseModel):
+ """One installed MCP, as shown in the user's library.
+
+ The rendered ``mcp_config`` is deliberately left out: it carries the
+ inputs the user filled in at install time, API keys included, and
+ nothing on this screen needs them.
+ """
+
+ id: str = Field(description="The installed-MCP record id.")
+ name: str = Field(description="The MCP name, unique for this user.")
+ is_stateful: bool = Field(description="Whether it needs a session.")
+ enabled: bool = Field(description="Whether the user has it turned on.")
+ display_name: str | None = Field(
+ default=None,
+ description="The card's user-facing name at install time.",
+ )
+ description: str = Field(
+ default="",
+ description="The card's description at install time.",
+ )
+ tags: list[str] = Field(
+ default_factory=list,
+ description="The card's tags at install time.",
+ )
+ author: str | None = Field(
+ default=None,
+ description="Who published the MCP, at install time.",
+ )
+ icon_url: str | None = Field(
+ default=None,
+ description="The card's icon at install time.",
+ )
+ url: str | None = Field(
+ default=None,
+ description="The MCP's page on the hub's website.",
+ )
+ hub_id: str | None = Field(
+ default=None,
+ description="The hub it came from, or null when added by hand.",
+ )
+ card_id: str | None = Field(
+ default=None,
+ description="The card's id on that hub.",
+ )
+ version: str | None = Field(
+ default=None,
+ description="The card version installed.",
+ )
+
+ @classmethod
+ def from_record(cls, record: MCPRecord) -> "MCPView":
+ """Project a stored record onto its secret-free view.
+
+ Args:
+ record (`MCPRecord`):
+ The stored record.
+
+ Returns:
+ `MCPView`:
+ The view safe to return to the client.
+ """
+ return cls(
+ id=record.id,
+ name=record.client.name,
+ is_stateful=record.client.is_stateful,
+ enabled=record.enabled,
+ display_name=record.display_name,
+ description=record.description,
+ tags=record.tags,
+ author=record.author,
+ icon_url=record.icon_url,
+ url=record.url,
+ hub_id=record.hub_id,
+ card_id=record.card_id,
+ version=record.version,
+ )
+
+
+class UpdateMCPRequest(BaseModel):
+ """The body of a library edit. Omitted fields are left alone."""
+
+ name: str | None = Field(
+ default=None,
+ description=(
+ "A new name. Must match ``[a-zA-Z0-9_-]+`` and stay unique "
+ "for this user."
+ ),
+ )
+ values: dict | None = Field(
+ default=None,
+ description=(
+ "New answers to the card's ``inputs_schema``, merged over "
+ "the stored ones — send only the keys that changed. The "
+ "config is re-rendered from the card, so this needs the "
+ "originating hub to still be registered and reachable."
+ ),
+ )
+ enabled: bool | None = Field(
+ default=None,
+ description="Whether the MCP is turned on.",
+ )
diff --git a/src/agentscope/app/_router/_schema/_hub_skill.py b/src/agentscope/app/_router/_schema/_hub_skill.py
new file mode 100644
index 000000000..c793ee220
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_hub_skill.py
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+"""Schemas for skills installed from a hub."""
+from pydantic import BaseModel, Field
+
+from ...storage import SkillRecord
+
+
+class SkillView(BaseModel):
+ """One installed skill, as shown in the user's library."""
+
+ id: str = Field(description="The installed-skill record id.")
+ name: str = Field(description="The skill name, unique for this user.")
+ enabled: bool = Field(description="Whether the user has it turned on.")
+ display_name: str | None = Field(
+ default=None,
+ description="The card's user-facing name at install time.",
+ )
+ description: str = Field(
+ default="",
+ description="The card's description at install time.",
+ )
+ tags: list[str] = Field(
+ default_factory=list,
+ description="The card's tags at install time.",
+ )
+ author: str | None = Field(
+ default=None,
+ description="Who published the skill, at install time.",
+ )
+ icon_url: str | None = Field(
+ default=None,
+ description="The card's icon at install time.",
+ )
+ url: str | None = Field(
+ default=None,
+ description="The skill's page on the hub's website.",
+ )
+ hub_id: str | None = Field(
+ default=None,
+ description="The hub it came from, or null when added by hand.",
+ )
+ card_id: str | None = Field(
+ default=None,
+ description="The card's id on that hub.",
+ )
+ version: str | None = Field(
+ default=None,
+ description="The card version installed.",
+ )
+
+ @classmethod
+ def from_record(cls, record: SkillRecord) -> "SkillView":
+ """Project a stored record onto its list view.
+
+ The ``SKILL.md`` body is left out — it is long enough to bloat a
+ list response, and only a detail view needs it.
+
+ Args:
+ record (`SkillRecord`):
+ The stored record.
+
+ Returns:
+ `SkillView`:
+ The view shown in the library list.
+ """
+ return cls(
+ id=record.id,
+ name=record.name,
+ enabled=record.enabled,
+ display_name=record.display_name,
+ description=record.description,
+ tags=record.tags,
+ author=record.author,
+ icon_url=record.icon_url,
+ url=record.url,
+ hub_id=record.hub_id,
+ card_id=record.card_id,
+ version=record.version,
+ )
diff --git a/src/agentscope/app/_router/_schema/_workspace.py b/src/agentscope/app/_router/_schema/_workspace.py
new file mode 100644
index 000000000..40b905fa4
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_workspace.py
@@ -0,0 +1,70 @@
+# -*- coding: utf-8 -*-
+"""Schemas for equipping a workspace with MCPs and skills."""
+from pydantic import BaseModel, Field
+
+from ....mcp import MCPClient
+
+
+class AddSkillRequest(BaseModel):
+ """The request to add skill."""
+
+ skill_path: str
+
+
+class AddFromLibraryRequest(BaseModel):
+ """The request to put library MCPs into a workspace."""
+
+ mcp_ids: list[str] = Field(
+ description="The installed-MCP record ids to add.",
+ )
+
+
+class AddSkillsFromLibraryRequest(BaseModel):
+ """The request to put library skills into a workspace."""
+
+ skill_ids: list[str] = Field(
+ description="The installed-skill record ids to add.",
+ )
+
+
+class AddFromLibraryResponse(BaseModel):
+ """What landed, and what did not.
+
+ Reported per item rather than as one status: installing is done one
+ at a time, so a bad API key on the third pick must not throw away
+ the two that worked.
+ """
+
+ added: list[str] = Field(
+ default_factory=list,
+ description=(
+ "The names now in the workspace. Excludes ones already "
+ "present, which are skipped rather than re-added."
+ ),
+ )
+ failed: dict[str, str] = Field(
+ default_factory=dict,
+ description="Whatever could not be added, mapped to why.",
+ )
+
+
+class ToolInfo(BaseModel):
+ """The tool info."""
+
+ name: str
+ description: str | None = None
+
+
+class MCPClientStatus(MCPClient):
+ """MCPClient enriched with live tool list and health status."""
+
+ is_healthy: bool = False
+ tools: list[ToolInfo] = Field(default_factory=list)
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Why listing this MCP's tools failed. A red dot alone leaves "
+ "the user with nothing to act on — a wrong API key, an "
+ "unreachable host and a missing command all look the same."
+ ),
+ )
diff --git a/src/agentscope/app/_router/_skill.py b/src/agentscope/app/_router/_skill.py
new file mode 100644
index 000000000..13614d713
--- /dev/null
+++ b/src/agentscope/app/_router/_skill.py
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+"""Skill router — the user's own library of installed skills.
+
+The skill counterpart of :mod:`._mcp`: this is the user-level collection
+an install lands in, distinct from ``/workspace/skill``, which manages
+the skills present in one session's workspace.
+"""
+from fastapi import APIRouter, Depends, HTTPException, status
+
+from ..deps import get_current_user_id, get_storage
+from ..storage import SkillRecord, StorageBase
+from ._schema import SkillView
+
+skill_router = APIRouter(prefix="/skill", tags=["skill"])
+
+
+@skill_router.get("")
+async def list_skills(
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+) -> list[SkillView]:
+ """Return every skill the user has installed, ordered by name."""
+ records = await storage.list_skills(user_id)
+ return sorted(
+ (SkillView.from_record(r) for r in records),
+ key=lambda view: view.name,
+ )
+
+
+@skill_router.get("/{skill_id}")
+async def get_skill(
+ skill_id: str,
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+) -> SkillRecord:
+ """Return one installed skill, including its ``SKILL.md`` body."""
+ record = await storage.get_skill(user_id, skill_id)
+ if record is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"No installed skill with id {skill_id!r}.",
+ )
+ return record
+
+
+@skill_router.delete("/{skill_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_skill(
+ skill_id: str,
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+) -> None:
+ """Remove a skill from the user's library.
+
+ Workspaces that already hold this skill keep their copy — the files
+ were extracted into the workspace, and this record was only where
+ they came from.
+ """
+ if not await storage.delete_skill(user_id, skill_id):
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"No installed skill with id {skill_id!r}.",
+ )
diff --git a/src/agentscope/app/_router/_workspace.py b/src/agentscope/app/_router/_workspace.py
index eb3236cce..4dcdb2d39 100644
--- a/src/agentscope/app/_router/_workspace.py
+++ b/src/agentscope/app/_router/_workspace.py
@@ -1,42 +1,49 @@
# -*- coding: utf-8 -*-
"""Workspace router — manage MCP clients and skills on a workspace."""
-from fastapi import APIRouter, Depends, HTTPException, Query, status
-from pydantic import BaseModel, Field
+from fastapi import (
+ APIRouter,
+ Depends,
+ File,
+ Form,
+ HTTPException,
+ Query,
+ UploadFile,
+ status,
+)
+from pydantic import ValidationError
from ..deps import (
get_current_user_id,
+ get_skill_hubs,
get_storage,
get_workspace_manager,
)
+from ..hub import SkillHubBase
+from .._service._skill_upload import (
+ SkillUploadError,
+ UploadManifest,
+ _install_slots,
+ _tar_stream,
+ _validate_manifest,
+)
from ..workspace_manager import WorkspaceManagerBase
-from ..storage import StorageBase
+from ..storage import MCPRecord, StorageBase
from ...mcp import MCPClient
from ...skill import Skill
from ...workspace import WorkspaceBase
+from ._schema import (
+ AddFromLibraryRequest,
+ AddFromLibraryResponse,
+ AddSkillRequest,
+ AddSkillsFromLibraryRequest,
+ MCPClientStatus,
+ ToolInfo,
+)
+from ..._utils._common import _describe_exception
workspace_router = APIRouter(prefix="/workspace", tags=["workspace"])
-class AddSkillRequest(BaseModel):
- """The request to add skill."""
-
- skill_path: str
-
-
-class ToolInfo(BaseModel):
- """The tool info."""
-
- name: str
- description: str | None = None
-
-
-class MCPClientStatus(MCPClient):
- """MCPClient enriched with live tool list and health status."""
-
- is_healthy: bool = False
- tools: list[ToolInfo] = Field(default_factory=list)
-
-
async def _resolve_workspace(
user_id: str,
agent_id: str,
@@ -44,8 +51,28 @@ async def _resolve_workspace(
storage: StorageBase,
workspace_manager: WorkspaceManagerBase,
) -> WorkspaceBase:
- """Resolve the workspace for the given session, raising 404 if not
- found."""
+ """Return the workspace backing the given session.
+
+ Args:
+ user_id (`str`):
+ The authenticated user ID.
+ agent_id (`str`):
+ The agent owning the session.
+ session_id (`str`):
+ The session whose workspace is wanted.
+ storage (`StorageBase`):
+ The storage used to look the session record up.
+ workspace_manager (`WorkspaceManagerBase`):
+ The manager that opens or reattaches the workspace.
+
+ Returns:
+ `WorkspaceBase`:
+ The session's workspace.
+
+ Raises:
+ `HTTPException`:
+ ``404`` when the session does not exist.
+ """
session_record = await storage.get_session(user_id, agent_id, session_id)
if session_record is None:
raise HTTPException(
@@ -99,11 +126,12 @@ async def list_mcps(
tools=tools,
),
)
- except Exception:
+ except Exception as e:
results.append(
MCPClientStatus(
**base,
is_healthy=False,
+ error=_describe_exception(e),
),
)
@@ -119,7 +147,14 @@ async def add_mcp(
storage: StorageBase = Depends(get_storage),
workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
) -> None:
- """Add an MCP client to the session's workspace."""
+ """Add an MCP client to the session's workspace.
+
+ The MCP is also recorded in the user's library, so one typed in by
+ hand is reusable in the next session instead of being retyped. An
+ existing record of the same name is left alone: the library is where
+ that MCP is defined, and adding it to a second workspace must not
+ silently redefine it.
+ """
workspace = await _resolve_workspace(
user_id,
agent_id,
@@ -129,6 +164,63 @@ async def add_mcp(
)
await workspace.add_mcp(mcp)
+ if await storage.get_mcp_by_name(user_id, mcp.name) is None:
+ # No hub_id or card_id — this one has no card behind it, which
+ # is what tells the library it cannot be re-keyed or upgraded.
+ await storage.upsert_mcp(
+ user_id,
+ MCPRecord(user_id=user_id, client=mcp),
+ )
+
+
+@workspace_router.post(
+ "/mcp/from-library",
+ status_code=status.HTTP_201_CREATED,
+)
+async def add_mcps_from_library(
+ body: AddFromLibraryRequest,
+ agent_id: str = Query(...),
+ session_id: str = Query(...),
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+ workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+) -> AddFromLibraryResponse:
+ """Put MCPs the user has already installed into this workspace.
+
+ The rendered config never leaves the server, so the client sends ids
+ rather than configs — it has no way to reconstruct one.
+
+ Adding is per-MCP: one that fails to connect does not cancel the
+ rest, and the response says which ones landed.
+ """
+ workspace = await _resolve_workspace(
+ user_id,
+ agent_id,
+ session_id,
+ storage,
+ workspace_manager,
+ )
+ present = {client.name for client in await workspace.list_mcps()}
+
+ added: list[str] = []
+ failed: dict[str, str] = {}
+ for mcp_id in body.mcp_ids:
+ record = await storage.get_mcp(user_id, mcp_id)
+ if record is None:
+ failed[mcp_id] = "Not in your library."
+ continue
+ if record.client.name in present:
+ # Already there: not an error, just nothing to do.
+ continue
+ try:
+ await workspace.add_mcp(record.client)
+ except Exception as e:
+ failed[record.client.name] = _describe_exception(e)
+ continue
+ added.append(record.client.name)
+
+ return AddFromLibraryResponse(added=added, failed=failed)
+
@workspace_router.delete(
"/mcp/{mcp_name}",
@@ -177,7 +269,11 @@ async def list_skills(
return await workspace.list_skills()
-@workspace_router.post("/skill", status_code=status.HTTP_201_CREATED)
+@workspace_router.post(
+ "/skill",
+ status_code=status.HTTP_201_CREATED,
+ deprecated=True,
+)
async def add_skill(
body: AddSkillRequest,
agent_id: str = Query(...),
@@ -186,7 +282,13 @@ async def add_skill(
storage: StorageBase = Depends(get_storage),
workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
) -> None:
- """Add a skill to the session's workspace from the given path."""
+ """Add a skill to the session's workspace from the given path.
+
+ Deprecated: the path is resolved on the server, which only means
+ anything for a single-host deployment. Use ``POST /skill/upload``
+ to send a folder, or ``POST /skill/from-library`` to install one
+ the user already has.
+ """
workspace = await _resolve_workspace(
user_id,
agent_id,
@@ -197,6 +299,130 @@ async def add_skill(
await workspace.add_skill(body.skill_path)
+@workspace_router.post(
+ "/skill/upload",
+ status_code=status.HTTP_201_CREATED,
+)
+async def upload_skill(
+ manifest: str = Form(
+ description=(
+ "JSON ``{entries: [{path, size}]}`` describing the parts, "
+ "in the order they are sent."
+ ),
+ ),
+ files: list[UploadFile] = File(description="The folder's files."),
+ agent_id: str = Query(...),
+ session_id: str = Query(...),
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+ workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+) -> None:
+ """Install a skill from an uploaded folder.
+
+ The parts are re-tarred on the fly and piped into the workspace, so
+ the archive is never held whole. The manifest is what the client
+ claims; every limit in it is re-checked here, and the byte counts
+ are verified as the tar is built.
+ """
+ try:
+ parsed = UploadManifest.model_validate_json(manifest)
+ _validate_manifest(parsed)
+ except (ValidationError, SkillUploadError) as e:
+ raise HTTPException(
+ status.HTTP_422_UNPROCESSABLE_ENTITY,
+ str(e),
+ ) from e
+
+ if len(files) != len(parsed.entries):
+ raise HTTPException(
+ status.HTTP_422_UNPROCESSABLE_ENTITY,
+ f"The manifest lists {len(parsed.entries)} files but "
+ f"{len(files)} were sent.",
+ )
+
+ workspace = await _resolve_workspace(
+ user_id,
+ agent_id,
+ session_id,
+ storage,
+ workspace_manager,
+ )
+ async with _install_slots:
+ try:
+ # dir_name is unused: the tar members already carry the
+ # picked folder as their first path segment.
+ await workspace.add_skill_archive(
+ _tar_stream(parsed, files),
+ "tar",
+ "skill",
+ )
+ except (SkillUploadError, ValueError) as e:
+ raise HTTPException(
+ status.HTTP_422_UNPROCESSABLE_ENTITY,
+ str(e),
+ ) from e
+
+
+@workspace_router.post(
+ "/skill/from-library",
+ status_code=status.HTTP_201_CREATED,
+)
+async def add_skills_from_library(
+ body: AddSkillsFromLibraryRequest,
+ agent_id: str = Query(...),
+ session_id: str = Query(...),
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+ workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ skill_hubs: dict[str, SkillHubBase] = Depends(get_skill_hubs),
+) -> AddFromLibraryResponse:
+ """Put skills the user has already installed into this workspace.
+
+ Each one is re-downloaded from its hub and piped into the
+ workspace; the server holds no copy in between. Adding is
+ per-skill, and the response says which ones landed.
+ """
+ workspace = await _resolve_workspace(
+ user_id,
+ agent_id,
+ session_id,
+ storage,
+ workspace_manager,
+ )
+
+ added: list[str] = []
+ failed: dict[str, str] = {}
+ for skill_id in body.skill_ids:
+ record = await storage.get_skill(user_id, skill_id)
+ if record is None:
+ failed[skill_id] = "Not in your library."
+ continue
+ hub = skill_hubs.get(record.hub_id or "")
+ if hub is None:
+ failed[
+ record.name
+ ] = f"Its hub {record.hub_id!r} is no longer registered."
+ continue
+ try:
+ async with _install_slots:
+ archive = await hub.download(
+ user_id,
+ record.card_id or record.name,
+ record.version,
+ )
+ await workspace.add_skill_archive(
+ archive.stream,
+ archive.format,
+ record.name,
+ )
+ except Exception as e: # pylint: disable=broad-except
+ failed[record.name] = _describe_exception(e)
+ continue
+ added.append(record.name)
+
+ return AddFromLibraryResponse(added=added, failed=failed)
+
+
@workspace_router.delete(
"/skill/{skill_name}",
status_code=status.HTTP_204_NO_CONTENT,
diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.py
index 2d6648368..5ab3bd9c6 100644
--- a/src/agentscope/app/_service/__init__.py
+++ b/src/agentscope/app/_service/__init__.py
@@ -12,6 +12,7 @@ from ._index_sweeper import IndexSweeper
from ._index_task_consumer import IndexTaskConsumer
from ._index_worker import IndexWorker
from ._knowledge_base import KnowledgeBaseService
+from ._mcp_render import MCPRenderError, render_mcp
from ._model import get_model
from ._tts_model import get_tts_model
from ._session import SessionService, SessionStatus
@@ -28,6 +29,7 @@ __all__ = [
"IndexWorker",
"KnowledgeBaseService",
"KnowledgeBaseView",
+ "MCPRenderError",
"ResourceAccessService",
"SessionService",
"SessionStatus",
@@ -37,4 +39,5 @@ __all__ = [
"get_model",
"get_tts_model",
"get_toolkit",
+ "render_mcp",
]
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index 7935973d3..e96809b06 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -52,7 +52,8 @@ from ...event import (
ExternalExecutionResultEvent,
UserInterruptEvent,
)
-from ._errors import _classify_error
+from ._errors import _classify_error, _classify_setup_error
+from ..._utils._common import _generate_id
from ...message import AssistantMsg, Msg, ToolCallState
from ...permission import AdditionalWorkingDirectory
@@ -187,7 +188,9 @@ class ChatService:
persisted to the replay log and fanned out on the live channel
via :meth:`MessageBus.session_publish_event`. Exceptions are
logged and swallowed so a single failed fire does not tear
- down its trigger (HTTP request task, wakeup dispatcher, …).
+ down its trigger (HTTP request task, wakeup dispatcher, …);
+ reporting them to the client is :meth:`_run_impl`'s job, which
+ it does for every phase of the run.
Args:
user_id (`str`):
@@ -223,6 +226,131 @@ class ChatService:
str(e),
)
+ async def _close_failed_reply(
+ self,
+ session_id: str,
+ reply_msg: Msg,
+ error: Exception,
+ ) -> None:
+ """Close a reply that died mid-stream, and say why.
+
+ The stream never emitted its terminating ``ReplyEndEvent``, so
+ one is synthesized: publishing it stops the live SSE spinner,
+ and appending it gives the persisted reply a finished_at, reason
+ and error for anyone who refreshes.
+
+ Nothing is reported when the agent already closed the reply and
+ the failure is downstream (publish, projection): overwriting a
+ completed reply with an error would tell the user their answer
+ failed when it did not.
+
+ Args:
+ session_id (`str`):
+ The session the reply belongs to.
+ reply_msg (`Msg`):
+ The reply in flight.
+ error (`Exception`):
+ What killed the stream.
+ """
+ if reply_msg.finished_reason is not None:
+ logger.exception(
+ "Post-reply failure for session %r; the reply itself "
+ "completed.",
+ session_id,
+ )
+ return
+
+ end_event = ReplyEndEvent(
+ session_id=session_id,
+ reply_id=reply_msg.id,
+ finished_reason=ReplyFinishedReason.ERROR,
+ error=_classify_error(error),
+ )
+ reply_msg.append_event(end_event)
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ end_event.model_dump(mode="json"),
+ )
+ logger.exception(
+ "Reply failed for session %r; reported to the client as %s.",
+ session_id,
+ end_event.error.type if end_event.error else "error",
+ )
+
+ async def _report_failure(
+ self,
+ user_id: str,
+ session_id: str,
+ agent_id: str,
+ error: Exception,
+ ) -> None:
+ """Tell the client about a failure that reached no reply.
+
+ The caller is responsible for holding the session lock: these
+ events go on the same channel as a real reply's, so publishing
+ them unserialised would interleave a "reply failed" into an
+ answer another run is streaming. It is not taken here because
+ one call site already holds it.
+
+ Publishes a start/end pair so the failure lands the same way a
+ mid-reply one does — the UI has exactly one shape for "a reply
+ failed", and a stream that merely stops is not it. The pair is
+ persisted too, so the failure survives a refresh rather than
+ vanishing from the transcript.
+
+ Best-effort by construction: this runs on a path that has
+ already failed, so its own failure is logged and dropped rather
+ than replacing the error the caller is reporting.
+
+ Args:
+ user_id (`str`):
+ Authenticated caller's user ID.
+ session_id (`str`):
+ The session whose run failed.
+ agent_id (`str`):
+ The agent that was being assembled.
+ error (`Exception`):
+ What went wrong while setting the run up.
+ """
+ try:
+ reply_id = _generate_id()
+ start_event = ReplyStartEvent(
+ session_id=session_id,
+ reply_id=reply_id,
+ name=agent_id,
+ )
+ end_event = ReplyEndEvent(
+ session_id=session_id,
+ reply_id=reply_id,
+ finished_reason=ReplyFinishedReason.ERROR,
+ error=_classify_setup_error(error),
+ )
+
+ reply_msg = AssistantMsg(
+ id=reply_id,
+ name=agent_id,
+ content=[],
+ )
+ for event in (start_event, end_event):
+ reply_msg.append_event(event)
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ event.model_dump(mode="json"),
+ )
+ await self._storage.upsert_message(
+ user_id,
+ session_id,
+ reply_msg,
+ )
+ except Exception:
+ logger.exception(
+ "Failed to report a failure for session %r; the original "
+ "error is logged above.",
+ session_id,
+ )
+
async def interrupt(
self,
user_id: str,
@@ -282,6 +410,62 @@ class ChatService:
inputs=UserInterruptEvent(reply_id=session.state.reply_id),
)
+ @staticmethod
+ def _skip_parked_wakeup(
+ session_id: str,
+ agent: Agent,
+ input_msg: object,
+ ) -> bool:
+ """Whether a wake-up should be dropped rather than run.
+
+ Wake-ups deliver pending inbox content (team messages, etc.) by
+ poking the dispatcher to run the session with ``input_msg=None``.
+ If the agent is parked on an ``ASKING`` or ``SUBMITTED`` tool
+ call — waiting for user confirmation or external-execution
+ results — another ``None`` run would hit
+ :meth:`Agent._check_incoming_event`, which rightly rejects
+ ``None`` when there is something to confirm, and fail noisily.
+
+ The inbox content is safe to leave queued: whenever the user does
+ confirm (or the external result lands), the resuming run's next
+ reasoning step lets :class:`InboxMiddleware` drain it naturally.
+
+ Args:
+ session_id (`str`):
+ The session being woken, for the log line.
+ agent (`Agent`):
+ The assembled agent, whose context is inspected.
+ input_msg (`object`):
+ The run's input; only ``None`` marks a wake-up.
+
+ Returns:
+ `bool`:
+ ``True`` when the run should be skipped.
+ """
+ if input_msg is not None or not agent.state.context:
+ return False
+
+ last_msg = agent.state.context[-1]
+ if last_msg.role != "assistant" or last_msg.name != agent.name:
+ return False
+
+ awaiting = [
+ tc
+ for tc in last_msg.get_content_blocks("tool_call")
+ if tc.state in (ToolCallState.ASKING, ToolCallState.SUBMITTED)
+ ]
+ if not awaiting:
+ return False
+
+ logger.info(
+ "Skipping wake-up for session %s: agent is parked on %d "
+ "awaiting tool call(s); inbox messages will be drained when "
+ "the agent resumes.",
+ session_id,
+ len(awaiting),
+ )
+ return True
+
async def _run_impl(
self,
user_id: str,
@@ -298,244 +482,233 @@ class ChatService:
swallowing. Separated so the try/except doesn't bury the
per-step logic at one extra indentation level."""
- # ----------------------------------------------------------------
- # 1. Load records + resolve workspace ONCE here, reused below.
- # Reject missing records up front with a clear error so the
- # downstream assembly code can rely on non-None values.
- #
- # ``resolve_agent`` covers own agents (including team workers,
- # which the owner runs directly) and cross-owner shared agents
- # (viewer runs a shared user-source agent). It raises 404 when
- # the agent is not visible to the caller.
- # ----------------------------------------------------------------
+ # Steps 1-6 assemble the run; step 7 performs it. A failure
+ # here has no reply to attach to, so one is synthesized —
+ # otherwise the client sees a stream that simply stops and is
+ # left saying "unknown error".
try:
- agent_record = await self._access.resolve_agent(user_id, agent_id)
- except HTTPException as exc:
- raise HTTPException(
- status_code=404,
- detail=f"Agent {agent_id!r} not found.",
- ) from exc
- session_record = await self._storage.get_session(
- user_id,
- agent_id,
- session_id,
- )
- if session_record is None:
- raise HTTPException(
- status_code=404,
- detail=(
- f"Session {session_id!r} not found for "
- f"agent {agent_id!r}."
- ),
- )
- workspace = await self._workspace_manager.get_workspace(
- user_id,
- agent_id,
- session_id,
- session_record.config.workspace_id,
- )
-
- # Add workspace working directory to the permission context
- if (
- workspace.workdir
- not in session_record.state.permission_context.working_directories
- ):
- session_record.state.permission_context.working_directories[
- workspace.workdir
- ] = AdditionalWorkingDirectory(
- path=workspace.workdir,
- source="session",
- )
-
- # ----------------------------------------------------------------
- # 2. Middlewares — framework-supplied first, then caller extras.
- # Background-tool completions deliver their results via
- # ``message_bus.inbox_push + enqueue_wakeup``, so the dispatcher
- # (any process) wakes an idle session — no in-process retrigger
- # plumbing is needed here.
- # ----------------------------------------------------------------
- middlewares: list = [
- InboxMiddleware(self._message_bus),
- StateChangeMiddleware(
- message_bus=self._message_bus,
- session_id=session_id,
- ),
- ToolOffloadMiddleware(
- bg_manager=self._background_task_manager,
- message_bus=self._message_bus,
- user_id=user_id,
- agent_id=agent_id,
- ),
- ]
- if self._extra_agent_middlewares is not None:
- middlewares.extend(
- await self._extra_agent_middlewares(
+ # -----------------------------------------------------------------
+ # 1. Load records + resolve workspace ONCE here, reused below.
+ # Reject missing records up front with a clear error so the
+ # downstream assembly code can rely on non-None values.
+ #
+ # ``resolve_agent`` covers own agents (including team workers,
+ # which the owner runs directly) and cross-owner shared agents
+ # (viewer runs a shared user-source agent). It raises 404 when
+ # the agent is not visible to the caller.
+ # -----------------------------------------------------------------
+ try:
+ agent_record = await self._access.resolve_agent(
user_id,
agent_id,
- session_id,
- ),
+ )
+ except HTTPException as exc:
+ raise HTTPException(
+ status_code=404,
+ detail=f"Agent {agent_id!r} not found.",
+ ) from exc
+ session_record = await self._storage.get_session(
+ user_id,
+ agent_id,
+ session_id,
)
-
- # ----------------------------------------------------------------
- # 2b. TTS middleware — inject when the session has a TTS config.
- # ----------------------------------------------------------------
- tts_cfg = session_record.config.tts_model_config
- if tts_cfg is not None:
- tts_model = await get_tts_model(
+ if session_record is None:
+ raise HTTPException(
+ status_code=404,
+ detail=(
+ f"Session {session_id!r} not found for "
+ f"agent {agent_id!r}."
+ ),
+ )
+ workspace = await self._workspace_manager.get_workspace(
user_id,
- tts_cfg,
- self._access,
+ agent_id,
+ session_id,
+ session_record.config.workspace_id,
)
- middlewares.append(TTSMiddleware(tts_model))
-
- # ----------------------------------------------------------------
- # 2c. Knowledge-base middleware — inject when the session has KBs
- # attached. Each KB resolves to its own :class:`KnowledgeBase` handle
- # (own embedding model + vector store), so the middleware can
- # retrieve across heterogeneous KBs in one fan-out.
- #
- # Each KB may be either owned by the caller or shared to them
- # via the resource access policy. We resolve the owner through
- # ``resolve_knowledge_base`` first and hand the KB manager the
- # true owner id — its own storage lookups stay owner-scoped
- # and unaware of sharing.
- # ----------------------------------------------------------------
- kb_cfg = session_record.config.knowledge_config
- if (
- kb_cfg is not None
- and kb_cfg.knowledge_base_ids
- and self._knowledge_base_manager is not None
- ):
- knowledges: list[KnowledgeBase] = []
- for kb_id in kb_cfg.knowledge_base_ids:
- try:
- kb_record = await self._access.resolve_knowledge_base(
+
+ # Add workspace working directory to the permission context
+ working_dirs = (
+ session_record.state.permission_context.working_directories
+ )
+ if workspace.workdir not in working_dirs:
+ working_dirs[workspace.workdir] = AdditionalWorkingDirectory(
+ path=workspace.workdir,
+ source="session",
+ )
+
+ # ----------------------------------------------------------------
+ # 2. Middlewares — framework-supplied first, then caller extras.
+ # Background-tool completions deliver their results via
+ # ``message_bus.inbox_push + enqueue_wakeup``, so the dispatcher
+ # (any process) wakes an idle session — no in-process retrigger
+ # plumbing is needed here.
+ # -----------------------------------------------------------------
+ middlewares: list = [
+ InboxMiddleware(self._message_bus),
+ StateChangeMiddleware(
+ message_bus=self._message_bus,
+ session_id=session_id,
+ ),
+ ToolOffloadMiddleware(
+ bg_manager=self._background_task_manager,
+ message_bus=self._message_bus,
+ user_id=user_id,
+ agent_id=agent_id,
+ ),
+ ]
+ if self._extra_agent_middlewares is not None:
+ middlewares.extend(
+ await self._extra_agent_middlewares(
user_id,
- kb_id,
- )
- knowledge = (
- await self._knowledge_base_manager.get_knowledge(
- kb_record.user_id,
- kb_id,
- )
- )
- except Exception: # pylint: disable=broad-except
- # A KB the session referenced was deleted, its
- # sharing revoked, or its credential is gone —
- # log and skip so the chat turn can still run
- # with the remaining KBs.
- logger.exception(
- "Skipping knowledge base %r for session %r: "
- "failed to resolve runtime handle.",
- kb_id,
+ agent_id,
session_id,
- )
- continue
- knowledges.append(knowledge)
- if knowledges:
- middlewares.append(
- RAGMiddleware(
- knowledge_bases=knowledges,
- parameters=RAGMiddleware.Parameters(
- **(kb_cfg.parameters or {}),
- ),
),
)
- # ----------------------------------------------------------------
- # 3. Toolkit (workspace tools + planning + ToolStop + schedule +
- # team + extras + skills + mcps).
- # ----------------------------------------------------------------
- toolkit = await get_toolkit(
- storage=self._storage,
- workspace=workspace,
- workspace_manager=self._workspace_manager,
- scheduler_manager=self._scheduler_manager,
- background_task_manager=self._background_task_manager,
- message_bus=self._message_bus,
- middlewares=middlewares,
- user_id=user_id,
- agent_record=agent_record,
- session_record=session_record,
- resource_access_service=self._access,
- extra_factory=self._extra_agent_tools,
- sub_agent_templates=self._sub_agent_templates,
- )
+ # ----------------------------------------------------------------
+ # 2b. TTS middleware — inject when the session has a TTS config.
+ # -----------------------------------------------------------------
+ tts_cfg = session_record.config.tts_model_config
+ if tts_cfg is not None:
+ tts_model = await get_tts_model(
+ user_id,
+ tts_cfg,
+ self._access,
+ )
+ middlewares.append(TTSMiddleware(tts_model))
+
+ # ----------------------------------------------------------------
+ # 2c. Knowledge-base middleware — inject when the session has KBs
+ # attached. Each KB resolves to its own
+ # :class:`KnowledgeBase` handle
+ # (own embedding model + vector store), so the middleware can
+ # retrieve across heterogeneous KBs in one fan-out.
+ #
+ # Each KB may be either owned by the caller or shared to them
+ # via the resource access policy. We resolve the owner through
+ # ``resolve_knowledge_base`` first and hand the KB manager the
+ # true owner id — its own storage lookups stay owner-scoped
+ # and unaware of sharing.
+ # -----------------------------------------------------------------
+ kb_cfg = session_record.config.knowledge_config
+ if (
+ kb_cfg is not None
+ and kb_cfg.knowledge_base_ids
+ and self._knowledge_base_manager is not None
+ ):
+ knowledges: list[KnowledgeBase] = []
+ for kb_id in kb_cfg.knowledge_base_ids:
+ try:
+ kb_record = await self._access.resolve_knowledge_base(
+ user_id,
+ kb_id,
+ )
+ knowledge = (
+ await self._knowledge_base_manager.get_knowledge(
+ kb_record.user_id,
+ kb_id,
+ )
+ )
+ except Exception: # pylint: disable=broad-except
+ # A KB the session referenced was deleted, its
+ # sharing revoked, or its credential is gone —
+ # log and skip so the chat turn can still run
+ # with the remaining KBs.
+ logger.exception(
+ "Skipping knowledge base %r for session %r: "
+ "failed to resolve runtime handle.",
+ kb_id,
+ session_id,
+ )
+ continue
+ knowledges.append(knowledge)
+ if knowledges:
+ middlewares.append(
+ RAGMiddleware(
+ knowledge_bases=knowledges,
+ parameters=RAGMiddleware.Parameters(
+ **(kb_cfg.parameters or {}),
+ ),
+ ),
+ )
- # ----------------------------------------------------------------
- # 4. Model + fallback (resolved from session's config).
- # ----------------------------------------------------------------
- model_cfg = session_record.config.chat_model_config
- if not model_cfg:
- raise HTTPException(
- status_code=404,
- detail=f"No model configuration found for agent {agent_id}",
+ # ----------------------------------------------------------------
+ # 3. Toolkit (workspace tools + planning + ToolStop + schedule +
+ # team + extras + skills + mcps).
+ # -----------------------------------------------------------------
+ toolkit = await get_toolkit(
+ storage=self._storage,
+ workspace=workspace,
+ workspace_manager=self._workspace_manager,
+ scheduler_manager=self._scheduler_manager,
+ background_task_manager=self._background_task_manager,
+ message_bus=self._message_bus,
+ middlewares=middlewares,
+ user_id=user_id,
+ agent_record=agent_record,
+ session_record=session_record,
+ resource_access_service=self._access,
+ extra_factory=self._extra_agent_tools,
+ sub_agent_templates=self._sub_agent_templates,
)
- model = await get_model(user_id, model_cfg, self._access)
- fallback_cfg = session_record.config.fallback_chat_model_config
- fallback_model = (
- await get_model(user_id, fallback_cfg, self._access)
- if fallback_cfg is not None
- else None
- )
+ # ----------------------------------------------------------------
+ # 4. Model + fallback (resolved from session's config).
+ # -----------------------------------------------------------------
+ model_cfg = session_record.config.chat_model_config
+ if not model_cfg:
+ raise HTTPException(
+ status_code=404,
+ detail=(
+ f"No model configuration found for agent "
+ f"{agent_id}"
+ ),
+ )
+ model = await get_model(user_id, model_cfg, self._access)
- # ----------------------------------------------------------------
- # 5. Assemble the Agent.
- # ----------------------------------------------------------------
- agent_state = session_record.state
- agent_state.session_id = session_id
- agent = self._agent_cls(
- name=agent_record.data.name,
- system_prompt=agent_record.data.system_prompt,
- model=model,
- toolkit=toolkit,
- model_config=ModelConfig(fallback_model=fallback_model),
- context_config=agent_record.data.context_config,
- react_config=agent_record.data.react_config,
- state=agent_state,
- middlewares=middlewares,
- offloader=workspace,
- )
+ fallback_cfg = session_record.config.fallback_chat_model_config
+ fallback_model = (
+ await get_model(user_id, fallback_cfg, self._access)
+ if fallback_cfg is not None
+ else None
+ )
- # ----------------------------------------------------------------
- # 6. Guard: skip wake-up driven runs when the agent is parked on
- # an awaiting tool call.
- #
- # Wake-ups deliver pending inbox content (team messages, etc.) by
- # poking the dispatcher to run the session with ``input_msg=None``.
- # If the agent is currently parked on an ``ASKING`` or
- # ``SUBMITTED`` tool call (waiting for user confirmation or
- # external-execution results), kicking off another ``None`` run
- # would hit :meth:`Agent._check_incoming_event`, which rightly
- # rejects ``None`` when there is something to confirm — and fail
- # the run noisily. The inbox content is safe to leave queued:
- # whenever the user does confirm (or the external result lands),
- # the resuming run's next reasoning step lets
- # :class:`InboxMiddleware` drain the queue naturally.
- # ----------------------------------------------------------------
- if input_msg is None and agent.state.context:
- last_msg = agent.state.context[-1]
- if last_msg.role == "assistant" and last_msg.name == agent.name:
- awaiting = [
- tc
- for tc in last_msg.get_content_blocks("tool_call")
- if tc.state
- in (ToolCallState.ASKING, ToolCallState.SUBMITTED)
- ]
- if awaiting:
- logger.info(
- "Skipping wake-up for session %s: agent is parked "
- "on %d awaiting tool call(s); inbox messages will "
- "be drained when the agent resumes.",
- session_id,
- len(awaiting),
- )
- return
+ # ----------------------------------------------------------------
+ # 5. Assemble the Agent.
+ # -----------------------------------------------------------------
+ agent_state = session_record.state
+ agent_state.session_id = session_id
+ agent = self._agent_cls(
+ name=agent_record.data.name,
+ system_prompt=agent_record.data.system_prompt,
+ model=model,
+ toolkit=toolkit,
+ model_config=ModelConfig(fallback_model=fallback_model),
+ context_config=agent_record.data.context_config,
+ react_config=agent_record.data.react_config,
+ state=agent_state,
+ middlewares=middlewares,
+ offloader=workspace,
+ )
+
+ if self._skip_parked_wakeup(session_id, agent, input_msg):
+ return
+ except Exception as e: # pylint: disable=broad-except
+ # Under the session lock, like the reply this run never got
+ # to make: these events share a channel with a live reply's,
+ # so publishing them unserialised would drop a "reply failed"
+ # into the middle of an answer another run is streaming.
+ async with self._message_bus.acquire_lock(
+ MessageBusKeys.session_lock(session_id),
+ ttl_secs=MessageBusKeys.SESSION_RUN_TTL_SECS,
+ ):
+ await self._report_failure(user_id, session_id, agent_id, e)
+ return
- # ----------------------------------------------------------------
+ # --------------------------------------------------------------------
# 7. Run the agent inside the distributed session lock
- # ----------------------------------------------------------------
+ # ---------------------------------------------------------------------
lock_key = MessageBusKeys.session_lock(session_id)
events_key = MessageBusKeys.session_events(session_id)
async with self._message_bus.acquire_lock(
@@ -639,31 +812,20 @@ class ChatService:
current.cancel()
except Exception as e: # pylint: disable=broad-except
- # The reply stream died before emitting its terminating
- # ReplyEndEvent. Synthesize one so the reply is closed on
- # both channels (publish → live SSE stops loading;
- # append_event → persisted reply gets finished_at/reason/
- # error for refresh), then re-raise for logging + the
- # finally-persist. CancelledError is a BaseException, so
- # interrupts are unaffected; reply_msg is None only when we
- # failed before REPLY_START (nothing to close). The
- # finished_reason guard skips the case where the agent
- # already closed the reply and the failure is downstream
- # (publish/projection) — don't overwrite a completed reply.
- if reply_msg is not None and reply_msg.finished_reason is None:
- end_event = ReplyEndEvent(
- session_id=session_id,
- reply_id=reply_msg.id,
- finished_reason=ReplyFinishedReason.ERROR,
- error=_classify_error(e),
- )
- reply_msg.append_event(end_event)
- await publish_session_event(
- self._message_bus,
+ # CancelledError is a BaseException, so interrupts are
+ # unaffected. The lock is already held here, so the
+ # reporter is called directly.
+ if reply_msg is None:
+ # Failed before REPLY_START: nothing to close, so a
+ # fresh reply carries the failure instead.
+ await self._report_failure(
+ user_id,
session_id,
- end_event.model_dump(mode="json"),
+ agent_id,
+ e,
)
- raise
+ else:
+ await self._close_failed_reply(session_id, reply_msg, e)
finally:
# All persistence in a single coroutine, shielded from
diff --git a/src/agentscope/app/_service/_errors.py b/src/agentscope/app/_service/_errors.py
index 850be8f3b..f3e95203d 100644
--- a/src/agentscope/app/_service/_errors.py
+++ b/src/agentscope/app/_service/_errors.py
@@ -51,19 +51,35 @@ _GENERIC_MESSAGE: dict[ErrorType, str] = {
"Could not reach the model service — network error or timeout."
),
ErrorType.INTERNAL: "An unexpected internal error occurred.",
+ ErrorType.SETUP: (
+ "The session could not be prepared — check the agent's model, "
+ "tools and knowledge bases."
+ ),
ErrorType.UNKNOWN: "The reply failed with an unknown error.",
}
def _causes(e: BaseException) -> Iterator[BaseException]:
- """Yield ``e`` then its ``__cause__`` / ``__context__`` chain, guarding
- against cycles."""
+ """Yield ``e`` then everything it wraps, guarding against cycles.
+
+ Walks the ``__cause__`` / ``__context__`` chain and, for an
+ ``ExceptionGroup``, its members: async transports run inside task
+ groups, so a provider's 401 arrives as a leaf of a group whose own
+ message is ``"unhandled errors in a TaskGroup"``. Without descending
+ into it every such failure classifies as ``UNKNOWN``.
+ """
seen: set[int] = set()
- exc: BaseException | None = e
- while exc is not None and id(exc) not in seen:
- seen.add(id(exc))
- yield exc
- exc = exc.__cause__ or exc.__context__
+
+ def walk(exc: BaseException | None) -> Iterator[BaseException]:
+ while exc is not None and id(exc) not in seen:
+ seen.add(id(exc))
+ yield exc
+ if isinstance(exc, BaseExceptionGroup):
+ for sub in exc.exceptions:
+ yield from walk(sub)
+ exc = exc.__cause__ or exc.__context__
+
+ yield from walk(e)
def _extract_status(e: BaseException) -> int | None:
@@ -113,6 +129,31 @@ def _classify_type(e: Exception) -> ErrorType:
return ErrorType.UNKNOWN
+def _classify_setup_error(e: Exception) -> ErrorInfo:
+ """Classify a failure that happened before the agent replied.
+
+ Same rules as :func:`_classify_error`, except that what it cannot
+ place falls to ``SETUP`` rather than ``UNKNOWN``: at this point the
+ one thing known for certain is that preparing the run failed, and
+ saying so beats saying nothing.
+
+ Args:
+ e (`Exception`):
+ The exception raised while setting the run up.
+
+ Returns:
+ `ErrorInfo`:
+ The structured, UI-facing error description.
+ """
+ info = _classify_error(e)
+ if info.type is ErrorType.UNKNOWN:
+ return ErrorInfo(
+ type=ErrorType.SETUP,
+ message=_GENERIC_MESSAGE[ErrorType.SETUP],
+ )
+ return info
+
+
def _classify_error(e: Exception) -> ErrorInfo:
"""Classify a fatal reply exception into a structured
:class:`ErrorInfo` for the frontend.
diff --git a/src/agentscope/app/_service/_mcp_render.py b/src/agentscope/app/_service/_mcp_render.py
new file mode 100644
index 000000000..088476d87
--- /dev/null
+++ b/src/agentscope/app/_service/_mcp_render.py
@@ -0,0 +1,123 @@
+# -*- coding: utf-8 -*-
+"""Render an :class:`MCPCard` template into a connectable client."""
+from string import Template
+from typing import Any
+
+import jsonschema
+
+from ..hub import MCPCard
+from ...mcp import MCPClient
+
+
+class MCPRenderError(ValueError):
+ """Raised when user-supplied values do not fit an :class:`MCPCard`.
+
+ The single error type the install endpoint catches to answer 400 —
+ schema violations, unfilled placeholders and rejected client configs
+ all surface through it.
+ """
+
+
+def _substitute(
+ node: Any,
+ values: dict,
+ declared: set[str],
+ missing: set[str],
+) -> Any:
+ """Recursively substitute ``${...}`` in every string leaf.
+
+ Placeholders naming a declared input but absent from ``values`` are
+ collected into ``missing`` rather than raising, so the caller can
+ report them all at once.
+
+ Args:
+ node (`Any`):
+ The current node of the dumped config tree.
+ values (`dict`):
+ The user-supplied values keyed by input name.
+ declared (`set[str]`):
+ The input names declared by the card's ``inputs_schema``.
+ missing (`set[str]`):
+ The accumulator for declared-but-unsupplied placeholders.
+
+ Returns:
+ `Any`:
+ The node with its string leaves substituted.
+ """
+ if isinstance(node, str):
+ template = Template(node)
+ # Undeclared placeholders (e.g. a literal ``$HOME`` in stdio
+ # args) are deliberately left untouched by ``safe_substitute``.
+ identifiers = set(template.get_identifiers())
+ missing.update((identifiers & declared) - values.keys())
+ return template.safe_substitute(values)
+
+ if isinstance(node, dict):
+ return {
+ key: _substitute(value, values, declared, missing)
+ for key, value in node.items()
+ }
+
+ if isinstance(node, list):
+ return [_substitute(item, values, declared, missing) for item in node]
+
+ return node
+
+
+def render_mcp(
+ card: MCPCard,
+ values: dict,
+ name: str | None = None,
+) -> MCPClient:
+ """Turn a card plus the user's answers into a connectable client.
+
+ Args:
+ card (`MCPCard`):
+ The hub card carrying the config template and input schema.
+ values (`dict`):
+ The user-supplied values keyed by input name.
+ name (`str | None`, optional):
+ The name for the installed client. Defaults to the card name.
+
+ Returns:
+ `MCPClient`:
+ The client ready to hand to ``workspace.add_mcp``.
+
+ Raises:
+ `MCPRenderError`:
+ When ``values`` violate the card's ``inputs_schema``, leave a
+ declared placeholder unfilled, or produce a config the
+ client rejects.
+ """
+ try:
+ jsonschema.validate(values, card.inputs_schema)
+ except jsonschema.ValidationError as e:
+ raise MCPRenderError(
+ f"Invalid values for MCP {card.name!r}: {e.message}",
+ ) from e
+
+ declared = set(card.inputs_schema.get("properties", {}))
+ missing: set[str] = set()
+ config = _substitute(
+ card.config_template.model_dump(mode="json"),
+ values,
+ declared,
+ missing,
+ )
+
+ if missing:
+ raise MCPRenderError(
+ f"MCP {card.name!r} needs a value for: "
+ f"{', '.join(sorted(missing))}",
+ )
+
+ try:
+ return MCPClient(
+ name=name or card.name,
+ is_stateful=card.is_stateful,
+ mcp_config=config,
+ )
+ except ValueError as e:
+ raise MCPRenderError(
+ f"MCP {card.name!r} produced an invalid client: {e}",
+ ) from e
diff --git a/src/agentscope/app/_service/_skill_upload.py b/src/agentscope/app/_service/_skill_upload.py
new file mode 100644
index 000000000..64e3a8f71
--- /dev/null
+++ b/src/agentscope/app/_service/_skill_upload.py
@@ -0,0 +1,161 @@
+# -*- coding: utf-8 -*-
+"""Turn a browser folder upload into a tar stream for a workspace.
+
+The browser sends one part per file plus a manifest of paths and sizes.
+The manifest is what makes streaming possible at all: a tar header must
+carry the member size *before* its bytes, and multipart parts do not
+declare their length. Sizes are therefore taken on trust to build the
+headers and verified as the bytes go by — a mismatch aborts the install
+before anything is renamed into place.
+"""
+import asyncio
+import tarfile
+from typing import AsyncIterator
+
+from fastapi import UploadFile
+from pydantic import BaseModel, Field
+
+#: Ceilings on one upload. Peak memory is a chunk per concurrent
+#: install; these bound the sandbox's disk and the time a slot is held.
+MAX_FILE_BYTES = 50 * 1024 * 1024
+MAX_TOTAL_BYTES = 500 * 1024 * 1024
+MAX_FILE_COUNT = 100
+MAX_CONCURRENT_INSTALLS = 5
+
+_CHUNK_SIZE = 64 * 1024
+_TAR_BLOCK = 512
+
+#: Serializes installs process-wide, so a burst of uploads cannot
+#: multiply into an unbounded number of open sandbox writes.
+_install_slots = asyncio.Semaphore(MAX_CONCURRENT_INSTALLS)
+
+
+class SkillUploadError(ValueError):
+ """Raised when an upload is malformed or over a limit."""
+
+
+class UploadEntry(BaseModel):
+ """One file in a folder upload, as the browser described it."""
+
+ path: str = Field(
+ description=(
+ "The file's path relative to the picked folder's parent, "
+ "i.e. ``webkitRelativePath``."
+ ),
+ )
+ size: int = Field(ge=0, description="The file's size in bytes.")
+
+
+class UploadManifest(BaseModel):
+ """The declared contents of a folder upload."""
+
+ entries: list[UploadEntry]
+
+
+def _validate_manifest(manifest: UploadManifest) -> str:
+ """Check a manifest and return the skill's root directory name.
+
+ Args:
+ manifest (`UploadManifest`):
+ The declared upload contents.
+
+ Returns:
+ `str`:
+ The single top-level directory every path sits under.
+
+ Raises:
+ SkillUploadError:
+ If a limit is exceeded, a path is unsafe, the paths span
+ more than one root, or no ``SKILL.md`` is present.
+ """
+ entries = manifest.entries
+ if not entries:
+ raise SkillUploadError("The upload contains no files.")
+ if len(entries) > MAX_FILE_COUNT:
+ raise SkillUploadError(
+ f"A skill may hold at most {MAX_FILE_COUNT} files, "
+ f"got {len(entries)}.",
+ )
+
+ total = 0
+ roots: set[str] = set()
+ for entry in entries:
+ if entry.size > MAX_FILE_BYTES:
+ raise SkillUploadError(
+ f"{entry.path!r} is {entry.size} bytes, over the "
+ f"{MAX_FILE_BYTES}-byte per-file limit.",
+ )
+ total += entry.size
+
+ parts = entry.path.replace("\\", "/").split("/")
+ if len(parts) < 2 or any(p in ("", ".", "..") for p in parts):
+ raise SkillUploadError(f"Unsafe upload path: {entry.path!r}")
+ if entry.path.startswith("/"):
+ raise SkillUploadError(f"Unsafe upload path: {entry.path!r}")
+ roots.add(parts[0])
+
+ if total > MAX_TOTAL_BYTES:
+ raise SkillUploadError(
+ f"The upload is {total} bytes, over the "
+ f"{MAX_TOTAL_BYTES}-byte limit.",
+ )
+ if len(roots) != 1:
+ raise SkillUploadError(
+ f"A skill must be a single folder, got {sorted(roots)}.",
+ )
+
+ root = roots.pop()
+ if not any(e.path == f"{root}/SKILL.md" for e in manifest.entries):
+ raise SkillUploadError(
+ f"No SKILL.md at the root of {root!r}.",
+ )
+ return root
+
+
+async def _tar_stream(
+ manifest: UploadManifest,
+ files: list[UploadFile],
+) -> AsyncIterator[bytes]:
+ """Emit a tar of the uploaded files, chunk by chunk.
+
+ Args:
+ manifest (`UploadManifest`):
+ The validated manifest; its order must match ``files``.
+ files (`list[UploadFile]`):
+ The uploaded parts, in manifest order.
+
+ Yields:
+ `bytes`:
+ The next chunk of the tar archive.
+
+ Raises:
+ SkillUploadError:
+ If a part's real length differs from its declared size.
+ """
+ for entry, upload in zip(manifest.entries, files):
+ info = tarfile.TarInfo(name=entry.path)
+ info.size = entry.size
+ info.mtime = 0
+ yield info.tobuf(tarfile.GNU_FORMAT)
+
+ written = 0
+ while chunk := await upload.read(_CHUNK_SIZE):
+ written += len(chunk)
+ if written > entry.size:
+ raise SkillUploadError(
+ f"{entry.path!r} is larger than its declared "
+ f"{entry.size} bytes.",
+ )
+ yield chunk
+
+ if written != entry.size:
+ raise SkillUploadError(
+ f"{entry.path!r} declared {entry.size} bytes but sent "
+ f"{written}.",
+ )
+ padding = -entry.size % _TAR_BLOCK
+ if padding:
+ yield b"\0" * padding
+
+ # Two zero blocks mark the end of a tar archive.
+ yield b"\0" * (2 * _TAR_BLOCK)
diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.py
index b26dcfe49..255fb2575 100644
--- a/src/agentscope/app/deps.py
+++ b/src/agentscope/app/deps.py
@@ -15,6 +15,7 @@ from ._service import (
SessionService,
)
from ._types import AgentMiddlewareFactory, AgentToolFactory
+from .hub import MCPHubBase, SkillHubBase
from .message_bus import MessageBus
from .rag.blob_store import BlobStoreBase
from .rag.knowledge_base_manager import KnowledgeBaseManagerBase
@@ -313,3 +314,33 @@ async def get_knowledge_parsers(
),
)
return parsers
+
+
+async def get_mcp_hubs(request: Request) -> dict[str, MCPHubBase]:
+ """Return the registered MCP hubs, keyed by hub id.
+
+ Args:
+ request (`Request`):
+ The incoming FastAPI request.
+
+ Returns:
+ `dict[str, MCPHubBase]`:
+ The hubs stored in ``app.state.mcp_hubs``, empty when none
+ were passed to ``create_app``.
+ """
+ return getattr(request.app.state, "mcp_hubs", {})
+
+
+async def get_skill_hubs(request: Request) -> dict[str, SkillHubBase]:
+ """Return the registered skill hubs, keyed by hub id.
+
+ Args:
+ request (`Request`):
+ The incoming FastAPI request.
+
+ Returns:
+ `dict[str, SkillHubBase]`:
+ The hubs stored in ``app.state.skill_hubs``, empty when none
+ were passed to ``create_app``.
+ """
+ return getattr(request.app.state, "skill_hubs", {})
diff --git a/src/agentscope/app/hub/__init__.py b/src/agentscope/app/hub/__init__.py
new file mode 100644
index 000000000..7c4106ce8
--- /dev/null
+++ b/src/agentscope/app/hub/__init__.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+"""The hub classes, responsible for providing resource for the agent service.
+"""
+
+from ._base import HubBase
+from ._error import HubError
+from ._mcp import (
+ GitHubMCPHub,
+ MCPHubBase,
+ MCPCard,
+ MCPHubPage,
+)
+from ._skill import (
+ SkillArchive,
+ SkillHubBase,
+ SkillCard,
+ SkillHubPage,
+ ClawSkillHub,
+)
+
+__all__ = [
+ "HubBase",
+ "HubError",
+ "GitHubMCPHub",
+ "MCPHubBase",
+ "MCPCard",
+ "MCPHubPage",
+ "SkillArchive",
+ "SkillHubBase",
+ "SkillCard",
+ "SkillHubPage",
+ "ClawSkillHub",
+]
diff --git a/src/agentscope/app/hub/_base.py b/src/agentscope/app/hub/_base.py
new file mode 100644
index 000000000..f4ccd99bf
--- /dev/null
+++ b/src/agentscope/app/hub/_base.py
@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+"""The shared hub identity and lifecycle."""
+import re
+from typing import Any, Self
+
+# A hub id is a path segment in the hub routes.
+HUB_ID_PATTERN = re.compile(r"[a-zA-Z0-9_-]+")
+
+
+class HubBase:
+ """The identity and lifecycle shared by every hub implementation.
+
+ A hub is addressed by :attr:`hub_id` in the HTTP routes, and a card
+ is addressed globally by the ``(hub_id, card_id)`` pair, so the id
+ must stay stable across restarts.
+
+ Hubs are entered once by the app lifespan and live as long as the
+ process, so an implementation talking to a registry over HTTP can
+ hold one client across requests instead of paying for a fresh
+ handshake on every page of a catalog.
+ """
+
+ def __init__(
+ self,
+ hub_id: str,
+ display_name: str,
+ description: str = "",
+ icon_url: str | None = None,
+ ) -> None:
+ """Initialize the hub identity.
+
+ Args:
+ hub_id (`str`):
+ The stable identifier addressing this hub. Must match
+ ``[a-zA-Z0-9_-]+`` and be unique among the hubs of the
+ same kind registered on one app.
+ display_name (`str`):
+ The user-facing hub name.
+ description (`str`, defaults to `""`):
+ The user-facing hub description.
+ icon_url (`str | None`, optional):
+ An image identifying the hub in the picker. ``None``
+ leaves the UI to fall back rather than show a gap.
+
+ Raises:
+ `ValueError`:
+ When ``hub_id`` is not usable as a URL path segment.
+ """
+ if not HUB_ID_PATTERN.fullmatch(hub_id):
+ raise ValueError(
+ f"Hub id {hub_id!r} must match [a-zA-Z0-9_-]+ so it is "
+ f"usable as a route path segment.",
+ )
+ self.hub_id = hub_id
+ self.display_name = display_name
+ self.description = description
+ self.icon_url = icon_url
+
+ async def __aenter__(self) -> Self:
+ """Enter the hub — open whatever it talks to the registry with.
+
+ The default is a no-op, so a hub with nothing to open needs no
+ boilerplate.
+
+ Returns:
+ `HubBase`:
+ ``self``.
+ """
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ """Exit the hub — close what :meth:`__aenter__` opened."""
diff --git a/src/agentscope/app/hub/_error.py b/src/agentscope/app/hub/_error.py
new file mode 100644
index 000000000..5d1f2017b
--- /dev/null
+++ b/src/agentscope/app/hub/_error.py
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+"""The failure shared by every hub."""
+
+
+class HubError(Exception):
+ """Raised when a hub's upstream registry returns a failure.
+
+ One type for every hub: the registries differ but the failure does
+ not, and a caller that wants to map an upstream 429 onto a 503 has
+ to catch something. ``hub_id`` says which hub failed, so a page
+ listing several of them can name the one at fault.
+ """
+
+ def __init__(self, hub_id: str, status_code: int, message: str) -> None:
+ """Initialize the error.
+
+ Args:
+ hub_id (`str`):
+ The hub whose upstream failed.
+ status_code (`int`):
+ The HTTP status code the registry returned.
+ message (`str`):
+ The response body, surfaced verbatim — public registry
+ errors are plain text and worth showing.
+ """
+ self.hub_id = hub_id
+ self.status_code = status_code
+ self.message = message
+ super().__init__(f"{hub_id} returned {status_code}: {message}")
diff --git a/src/agentscope/app/hub/_mcp/__init__.py b/src/agentscope/app/hub/_mcp/__init__.py
new file mode 100644
index 000000000..f23125811
--- /dev/null
+++ b/src/agentscope/app/hub/_mcp/__init__.py
@@ -0,0 +1,13 @@
+# -*- coding: utf-8 -*-
+"""The MCP Hub classes."""
+
+from ._base import MCPHubBase
+from ._card import MCPCard, MCPHubPage
+from ._github_hub import GitHubMCPHub
+
+__all__ = [
+ "GitHubMCPHub",
+ "MCPHubBase",
+ "MCPCard",
+ "MCPHubPage",
+]
diff --git a/src/agentscope/app/hub/_mcp/_base.py b/src/agentscope/app/hub/_mcp/_base.py
new file mode 100644
index 000000000..fd5d49f24
--- /dev/null
+++ b/src/agentscope/app/hub/_mcp/_base.py
@@ -0,0 +1,69 @@
+# -*- coding: utf-8 -*-
+"""The MCP hub base class."""
+from abc import ABC, abstractmethod
+
+from ._card import MCPCard, MCPHubPage
+from .._base import HubBase
+
+
+class MCPHubBase(HubBase, ABC):
+ """The base class for MCP hub implementations.
+
+ A hub exposes a browsable catalog of :class:`MCPCard` templates.
+ Turning a card into a connectable ``MCPClient`` is the installer's
+ job, not the hub's — see :func:`agentscope.app._service.render_mcp`.
+ """
+
+ @abstractmethod
+ async def list_mcps(
+ self,
+ user_id: str,
+ q: str | None = None,
+ cursor: str | None = None,
+ limit: int = 20,
+ ) -> MCPHubPage:
+ """Browse the hub catalog.
+
+ Pagination is cursor-based rather than page-numbered: registries
+ commonly expose only a forward cursor and no total count, and an
+ offset-based hub can always encode its offset into the cursor.
+
+ Args:
+ user_id (`str`):
+ The user identifier to query MCP cards for.
+ q (`str | None`, optional):
+ A keyword filtering the cards. When ``None`` the whole
+ catalog is browsed.
+ cursor (`str | None`, optional):
+ The opaque cursor from a previous page. When ``None`` the
+ first page is returned.
+ limit (`int`, defaults to `20`):
+ The maximum number of cards per page.
+
+ Returns:
+ `MCPHubPage`:
+ The requested page of cards plus the next cursor.
+ """
+
+ @abstractmethod
+ async def get_mcp(
+ self,
+ user_id: str,
+ card_id: str,
+ ) -> MCPCard:
+ """Fetch a single card by its hub-local id.
+
+ Args:
+ user_id (`str`):
+ The user identifier to query the card for.
+ card_id (`str`):
+ The :attr:`MCPCard.id` addressing the card on this hub.
+
+ Returns:
+ `MCPCard`:
+ The matching card.
+
+ Raises:
+ `KeyError`:
+ When this hub has no card under ``card_id``.
+ """
diff --git a/src/agentscope/app/hub/_mcp/_card.py b/src/agentscope/app/hub/_mcp/_card.py
new file mode 100644
index 000000000..2e3c6959d
--- /dev/null
+++ b/src/agentscope/app/hub/_mcp/_card.py
@@ -0,0 +1,195 @@
+# -*- coding: utf-8 -*-
+"""The MCP card models."""
+from typing import Literal, Self
+
+from pydantic import BaseModel, Field, model_validator
+
+from ....mcp import StdioMCPConfig, HttpMCPConfig
+
+
+class MCPCard(BaseModel):
+ """A single MCP listing on a hub.
+
+ A card is a *template*, not a connectable client:
+ :attr:`config_template` carries ``${...}`` placeholders whose values
+ the user supplies at install time, described by
+ :attr:`inputs_schema`.
+
+ Two identifiers, deliberately separate:
+
+ - :attr:`id` addresses the card on its hub and is what
+ :attr:`ref` embeds. It may be any opaque string.
+ - :attr:`name` is the default name of the *installed* client, which
+ must match ``[a-zA-Z0-9_-]+`` because it composes the model-facing
+ tool name ``mcp__{name}__{tool}``. Cards are not rejected for a
+ bad name — the install call is, so browsing a registry with odd
+ slugs still works.
+ """
+
+ hub_id: str = Field(
+ title="Hub ID",
+ description="The id of the hub this card came from.",
+ )
+
+ id: str = Field(
+ default="",
+ title="ID",
+ description=(
+ "The identifier addressing this card on its hub. Defaults to "
+ "``name`` for registries that expose no separate id."
+ ),
+ )
+
+ name: str = Field(
+ title="Name",
+ description="The default name of the installed MCP client.",
+ )
+
+ display_name: str | None = Field(
+ default=None,
+ title="Display Name",
+ description="The user-facing name, falling back to ``name``.",
+ )
+
+ description: str = Field(
+ default="",
+ title="Description",
+ description="The user-facing description of the MCP.",
+ )
+
+ tags: list[str] = Field(
+ default_factory=list,
+ title="Tags",
+ description="The tags categorizing this card.",
+ )
+
+ version: str | None = Field(
+ default=None,
+ title="Version",
+ description="The card version reported by the hub.",
+ )
+
+ updated_at: float | None = Field(
+ default=None,
+ title="Updated At",
+ description="The last-updated timestamp (Unix epoch seconds).",
+ )
+
+ author: str | None = Field(
+ default=None,
+ title="Author",
+ description="Who published the MCP, when the hub says.",
+ )
+
+ icon_url: str | None = Field(
+ default=None,
+ title="Icon URL",
+ description=(
+ "An image representing the MCP. ``None`` when the hub offers "
+ "none — the UI is expected to fall back rather than show a "
+ "broken image."
+ ),
+ )
+
+ url: str | None = Field(
+ default=None,
+ title="URL",
+ description=(
+ "The MCP's page on the hub's website, for a 'view on the "
+ "hub' link. ``None`` when the hub has no web presence."
+ ),
+ )
+
+ readme: str | None = Field(
+ default=None,
+ title="Readme",
+ description=(
+ "The server's long-form documentation, shown in the detail "
+ "view where a skill shows its ``SKILL.md``. ``None`` when "
+ "the hub publishes none."
+ ),
+ )
+
+ installs: int | None = Field(
+ default=None,
+ title="Installs",
+ description=(
+ "How many times this MCP has been installed. ``None`` when "
+ "the hub does not count installs, which is not the same as "
+ "zero — render it only when set."
+ ),
+ )
+
+ downloads: int | None = Field(
+ default=None,
+ title="Downloads",
+ description=(
+ "How many times this MCP has been downloaded. ``None`` when "
+ "the hub does not count downloads."
+ ),
+ )
+
+ is_stateful: bool = Field(
+ default=True,
+ title="Stateful",
+ description=(
+ "Whether the installed client requires explicit connect() "
+ "and close(). Forwarded to ``MCPClient.is_stateful``."
+ ),
+ )
+
+ auth: Literal["none", "inputs"] = Field(
+ default="inputs",
+ title="Auth",
+ description=(
+ "How the user authenticates: ``none`` for public servers, "
+ "``inputs`` for the ``inputs_schema`` form. Reserved as a "
+ "discriminator so an ``oauth`` flow can be added later "
+ "without breaking the API."
+ ),
+ )
+
+ inputs_schema: dict = Field(
+ default_factory=dict,
+ title="Inputs Schema",
+ description=(
+ "A JSON Schema (``type: object``) describing the values the "
+ "user must supply. Secret fields carry the standard "
+ "``writeOnly: true`` and ``format: password`` keywords so "
+ "the frontend renders them masked."
+ ),
+ )
+
+ config_template: StdioMCPConfig | HttpMCPConfig = Field(
+ discriminator="type",
+ title="Config Template",
+ description=(
+ "The MCP config whose string leaves may hold ``${name}`` "
+ "placeholders referring to ``inputs_schema`` properties."
+ ),
+ )
+
+ @model_validator(mode="after")
+ def _default_id_to_name(self) -> Self:
+ """Fall back to ``name`` when the hub exposes no separate id."""
+ if not self.id:
+ self.id = self.name
+ return self
+
+
+class MCPHubPage(BaseModel):
+ """One page of MCP cards."""
+
+ cards: list[MCPCard] = Field(
+ title="Cards",
+ description="The cards on this page.",
+ )
+
+ next_cursor: str | None = Field(
+ default=None,
+ title="Next Cursor",
+ description=(
+ "The opaque cursor fetching the following page, or ``None`` "
+ "when this is the last one."
+ ),
+ )
diff --git a/src/agentscope/app/hub/_mcp/_github_hub.py b/src/agentscope/app/hub/_mcp/_github_hub.py
new file mode 100644
index 000000000..9edff93b3
--- /dev/null
+++ b/src/agentscope/app/hub/_mcp/_github_hub.py
@@ -0,0 +1,427 @@
+# -*- coding: utf-8 -*-
+"""The GitHub MCP Registry provider.
+
+A thin async client around GitHub's MCP registry
+(``https://api.mcp.github.com``), exposing its servers through the
+:class:`~agentscope.app.hub._mcp._base.MCPHubBase` interface.
+
+.. note:: The registry is public and needs no credentials. A GitHub token
+ only raises the rate limit.
+
+.. note:: A registry entry describes how to *reach* a server either as a
+ ``remote`` (an HTTP endpoint) or as a ``package`` (something to run
+ locally). Around a third of the catalog names a package without
+ saying how to run it — no ``runtime_hint`` and no ``registry_name`` —
+ and those entries are skipped rather than listed as cards that
+ cannot install. See :meth:`GitHubMCPHub.list_mcps`.
+"""
+import re
+from datetime import datetime
+from typing import TYPE_CHECKING, Any
+
+from ._base import MCPHubBase
+from ._card import MCPCard, MCPHubPage
+from .._error import HubError
+
+if TYPE_CHECKING:
+ import httpx
+
+DEFAULT_BASE_URL = "https://api.mcp.github.com"
+
+# The registry writes secret placeholders as ``{TOKEN}``; the renderer
+# uses ``string.Template``, which wants ``${TOKEN}``.
+_PLACEHOLDER = re.compile(r"(?<!\$)\{([A-Za-z_][A-Za-z0-9_]*)\}")
+
+# How to run a package, by the registry's ``runtime_hint``. Anything not
+# listed here cannot be turned into a command, so the entry is skipped.
+_RUNTIMES: dict[str, list[str]] = {
+ "npx": ["-y"],
+ "uvx": [],
+ "uv": ["tool", "run"],
+ "docker": ["run", "-i", "--rm"],
+}
+
+
+def _substitute(value: Any) -> Any:
+ """Rewrite ``{VAR}`` placeholders to the ``${VAR}`` the renderer wants.
+
+ Args:
+ value (`Any`):
+ A string, list or dict from the registry payload.
+
+ Returns:
+ `Any`:
+ The same structure with placeholders rewritten.
+ """
+ if isinstance(value, str):
+ return _PLACEHOLDER.sub(r"${\1}", value)
+ if isinstance(value, list):
+ return [_substitute(item) for item in value]
+ if isinstance(value, dict):
+ return {key: _substitute(item) for key, item in value.items()}
+ return value
+
+
+class GitHubMCPHub(MCPHubBase):
+ """An MCP hub backed by GitHub's MCP registry.
+
+ .. code-block:: python
+
+ hub = GitHubMCPHub()
+ page = await hub.list_mcps(user_id="alice", q="markdown")
+ """
+
+ def __init__(
+ self,
+ hub_id: str = "github",
+ display_name: str = "GitHub MCP Registry",
+ description: str = "MCP servers published to GitHub's registry.",
+ icon_url: str
+ | None = "https://avatars.githubusercontent.com/u/9919?s=64",
+ *,
+ base_url: str = DEFAULT_BASE_URL,
+ api_token: str | None = None,
+ timeout: float = 30.0,
+ ) -> None:
+ """Initialize the GitHub MCP registry provider.
+
+ Args:
+ hub_id (`str`, defaults to `"github"`):
+ The stable identifier addressing this hub in the routes.
+ display_name (`str`, defaults to `"GitHub MCP Registry"`):
+ The user-facing hub name.
+ description (`str`, optional):
+ The user-facing hub description.
+ icon_url (`str | None`, optional):
+ The hub's icon, defaulting to GitHub's avatar.
+ base_url (`str`, defaults to `"https://api.mcp.github.com"`):
+ The base URL of the registry.
+ api_token (`str | None`, optional):
+ A GitHub token. The registry is public; a token only
+ raises the rate limit.
+ timeout (`float`, defaults to `30.0`):
+ The per-request timeout in seconds.
+ """
+ super().__init__(hub_id, display_name, description, icon_url)
+ self.base_url = base_url.rstrip("/")
+ self.api_token = api_token
+ self.timeout = timeout
+ self._client: "httpx.AsyncClient | None" = None
+
+ async def __aenter__(self) -> "GitHubMCPHub":
+ """Open the HTTP client shared by every request.
+
+ Returns:
+ `GitHubMCPHub`:
+ ``self``.
+ """
+ import httpx
+
+ self._client = httpx.AsyncClient(timeout=self.timeout)
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ """Close the shared HTTP client."""
+ if self._client is not None:
+ await self._client.aclose()
+ self._client = None
+
+ async def _request(
+ self,
+ path: str,
+ params: dict | None = None,
+ ) -> "httpx.Response":
+ """Send a GET request to the registry.
+
+ Args:
+ path (`str`):
+ The request path under :attr:`base_url`.
+ params (`dict | None`, optional):
+ The query parameters.
+
+ Returns:
+ `httpx.Response`:
+ The successful response.
+
+ Raises:
+ `HubError`:
+ When the registry returns a non-success status code.
+ """
+ import httpx
+
+ headers = {"Accept": "application/json"}
+ if self.api_token:
+ headers["Authorization"] = f"Bearer {self.api_token}"
+
+ # Opened lazily as well as on __aenter__, so a hub used outside
+ # the app still works.
+ if self._client is None:
+ self._client = httpx.AsyncClient(timeout=self.timeout)
+ response = await self._client.get(
+ f"{self.base_url}{path}",
+ params=params,
+ headers=headers,
+ )
+ if response.status_code >= 400:
+ raise HubError(
+ self.hub_id,
+ response.status_code,
+ response.text,
+ )
+ return response
+
+ @staticmethod
+ def _from_remote(remote: dict) -> tuple[dict, dict]:
+ """Build an HTTP config plus its inputs from a ``remotes`` entry.
+
+ Args:
+ remote (`dict`):
+ One entry of the server's ``remotes`` list.
+
+ Returns:
+ `tuple[dict, dict]`:
+ The config template and the ``{name: description}`` of
+ the secrets it references.
+ """
+ secrets: dict[str, str] = {}
+ headers = {}
+ for header in remote.get("headers") or []:
+ value = header.get("value") or ""
+ # The registry omits the header name when the value already
+ # spells out the scheme, which in practice means bearer auth.
+ key = header.get("name") or "Authorization"
+ headers[key] = _substitute(value)
+ for match in _PLACEHOLDER.finditer(value):
+ secrets[match.group(1)] = header.get("description") or ""
+
+ config: dict = {"type": "http_mcp", "url": remote["url"]}
+ if headers:
+ config["headers"] = headers
+ return config, secrets
+
+ @staticmethod
+ def _from_package(package: dict) -> tuple[dict, dict] | None:
+ """Build a stdio config plus its inputs from a ``packages`` entry.
+
+ Args:
+ package (`dict`):
+ One entry of the server's ``packages`` list.
+
+ Returns:
+ `tuple[dict, dict] | None`:
+ The config template and its secrets, or ``None`` when the
+ registry does not say how to run the package.
+ """
+ runtime = package.get("runtime_hint")
+ if runtime not in _RUNTIMES:
+ return None
+
+ name = package.get("name")
+ if not name:
+ return None
+ version = package.get("version")
+ spec = f"{name}@{version}" if version and runtime == "npx" else name
+
+ env = {}
+ secrets: dict[str, str] = {}
+ for variable in package.get("environment_variables") or []:
+ key = variable.get("name")
+ if not key:
+ continue
+ env[key] = f"${{{key}}}"
+ if variable.get("is_secret"):
+ secrets[key] = variable.get("description") or ""
+
+ config: dict = {
+ "type": "stdio_mcp",
+ "command": runtime,
+ "args": [*_RUNTIMES[runtime], spec],
+ }
+ if env:
+ config["env"] = env
+ return config, secrets
+
+ def _to_card(self, entry: dict, readme: bool = False) -> MCPCard | None:
+ """Build a card from one registry entry.
+
+ Args:
+ entry (`dict`):
+ One record of the ``servers`` list.
+ readme (`bool`, defaults to `False`):
+ Whether to carry the README. Left out when listing —
+ they run to tens of kilobytes each, so a page of twenty
+ would be megabytes of text nothing on screen shows.
+
+ Returns:
+ `MCPCard | None`:
+ The card, or ``None`` when the entry describes no way to
+ reach the server.
+ """
+ server = entry.get("server") or {}
+ github = entry.get("x-github") or {}
+
+ built: tuple[dict, dict] | None = None
+ for remote in server.get("remotes") or []:
+ if remote.get("url"):
+ built = self._from_remote(remote)
+ break
+ if built is None:
+ for package in server.get("packages") or []:
+ built = self._from_package(package)
+ if built is not None:
+ break
+ if built is None:
+ return None
+
+ config, secrets = built
+ inputs_schema: dict = {}
+ if secrets:
+ inputs_schema = {
+ "type": "object",
+ "properties": {
+ key: {
+ "type": "string",
+ "title": key,
+ "description": description,
+ "writeOnly": True,
+ "format": "password",
+ }
+ for key, description in secrets.items()
+ },
+ "required": sorted(secrets),
+ }
+
+ name = server.get("name") or ""
+ owner = name.rsplit("/", 1)[0] if "/" in name else None
+ repository = server.get("repository") or {}
+
+ # Client names reach the model as ``mcp__{name}__{tool}`` and so
+ # must match [a-zA-Z0-9_-]+, while registry names look like
+ # ``io.github.upstash/context7``. Keep the last segment.
+ slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", name.rsplit("/", 1)[-1])
+
+ updated_at = None
+ stamp = server.get("updated_at")
+ if stamp:
+ try:
+ updated_at = datetime.fromisoformat(
+ stamp.replace("Z", "+00:00"),
+ ).timestamp()
+ except ValueError:
+ pass
+
+ return MCPCard(
+ hub_id=self.hub_id,
+ id=server["id"],
+ name=slug.strip("-") or "mcp",
+ display_name=github.get("display_name") or name,
+ description=server.get("description") or "",
+ tags=[github["primary_language"]]
+ if github.get("primary_language")
+ else [],
+ version=(server.get("version_detail") or {}).get("version"),
+ updated_at=updated_at,
+ author=github.get("name_with_owner", "").rsplit("/", 1)[0]
+ or owner,
+ icon_url=github.get("preferred_image")
+ or github.get("owner_avatar_url"),
+ url=repository.get("url"),
+ # The registry mirrors the repository README on both blocks;
+ # they agree, so either will do.
+ readme=(repository.get("readme") or github.get("readme"))
+ if readme
+ else None,
+ # STDIO servers must be stateful — the process is the session.
+ is_stateful=config["type"] == "stdio_mcp",
+ auth="inputs" if secrets else "none",
+ inputs_schema=inputs_schema,
+ config_template=config, # type: ignore[arg-type]
+ )
+
+ async def list_mcps(
+ self,
+ user_id: str,
+ q: str | None = None,
+ cursor: str | None = None,
+ limit: int = 20,
+ ) -> MCPHubPage:
+ """Browse the registry, one cursor page at a time.
+
+ ``q`` is applied here rather than upstream: the registry accepts
+ no search parameter, so a page is fetched and then filtered. A
+ page whose entries all filter out still carries a cursor, which
+ the caller is expected to follow.
+
+ Args:
+ user_id (`str`):
+ The user identifier. Unused by the public registry, kept
+ for interface compatibility.
+ q (`str | None`, optional):
+ A keyword matched against the name and description.
+ cursor (`str | None`, optional):
+ The opaque cursor from a previous page.
+ limit (`int`, defaults to `20`):
+ The maximum number of entries to fetch.
+
+ Returns:
+ `MCPHubPage`:
+ The cards of this page plus the next cursor.
+
+ Raises:
+ `HubError`:
+ When the registry returns a non-success status code.
+ """
+ params: dict = {"limit": limit}
+ if cursor is not None:
+ params["cursor"] = cursor
+
+ payload = (await self._request("/v0/servers", params)).json()
+
+ needle = (q or "").lower()
+ cards = []
+ for entry in payload.get("servers") or []:
+ card = self._to_card(entry)
+ if card is None:
+ continue
+ haystack = f"{card.name} {card.display_name} {card.description}"
+ if needle and needle not in haystack.lower():
+ continue
+ cards.append(card)
+
+ return MCPHubPage(
+ cards=cards,
+ next_cursor=(payload.get("metadata") or {}).get("next_cursor"),
+ )
+
+ async def get_mcp(self, user_id: str, card_id: str) -> MCPCard:
+ """Fetch one registry entry.
+
+ Args:
+ user_id (`str`):
+ The user identifier. Unused by the public registry, kept
+ for interface compatibility.
+ card_id (`str`):
+ The registry id of the server.
+
+ Returns:
+ `MCPCard`:
+ The card describing this server, README included.
+
+ Raises:
+ `KeyError`:
+ When the registry has no such server, or describes no way
+ to reach it.
+ `HubError`:
+ When the registry returns any other failure.
+ """
+ try:
+ response = await self._request(f"/v0/servers/{card_id}")
+ except HubError as e:
+ if e.status_code == 404:
+ raise KeyError(card_id) from e
+ raise
+
+ card = self._to_card(response.json(), readme=True)
+ if card is None:
+ raise KeyError(card_id)
+ return card
diff --git a/src/agentscope/app/hub/_skill/__init__.py b/src/agentscope/app/hub/_skill/__init__.py
new file mode 100644
index 000000000..dd73fbd3b
--- /dev/null
+++ b/src/agentscope/app/hub/_skill/__init__.py
@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+"""The skill hub classes."""
+
+from ._base import SkillArchive, SkillHubBase
+from ._card import SkillCard, SkillHubPage
+from ._claw_hub import ClawSkillHub
+
+__all__ = [
+ "SkillArchive",
+ "SkillHubBase",
+ "SkillCard",
+ "SkillHubPage",
+ "ClawSkillHub",
+]
diff --git a/src/agentscope/app/hub/_skill/_base.py b/src/agentscope/app/hub/_skill/_base.py
new file mode 100644
index 000000000..4bca7170a
--- /dev/null
+++ b/src/agentscope/app/hub/_skill/_base.py
@@ -0,0 +1,125 @@
+# -*- coding: utf-8 -*-
+"""The skill hub base class."""
+from abc import ABC, abstractmethod
+from typing import AsyncIterator, Literal, NamedTuple
+
+from ._card import SkillCard, SkillHubPage
+from .._base import HubBase
+
+
+class SkillArchive(NamedTuple):
+ """A skill archive as the hub serves it.
+
+ The format travels with the bytes so a hub can forward its upstream
+ response untouched — repacking to a fixed format would force every
+ hub to buffer the whole archive.
+
+ Attributes:
+ format: The archive format, as the installer must unpack it.
+ stream: The archive bytes, in order.
+ """
+
+ format: Literal["zip", "tar", "tar.gz"]
+ stream: AsyncIterator[bytes]
+
+
+class SkillHubBase(HubBase, ABC):
+ """The base class for skill hub implementations.
+
+ A hub exposes a browsable catalog of :class:`SkillCard` records plus
+ :meth:`download`, which streams the skill archive the installer
+ extracts into a workspace.
+ """
+
+ @abstractmethod
+ async def list_skills(
+ self,
+ user_id: str,
+ q: str | None = None,
+ cursor: str | None = None,
+ limit: int = 20,
+ ) -> SkillHubPage:
+ """Browse the hub catalog.
+
+ Implementations must not fetch per-card files here — listing a
+ page costs one upstream request, and ``SKILL.md`` is left to
+ :meth:`get_skill`.
+
+ Pagination is cursor-based rather than page-numbered: registries
+ commonly expose only a forward cursor and no total count, and an
+ offset-based hub can always encode its offset into the cursor.
+
+ Args:
+ user_id (`str`):
+ The user identifier to query skill cards for.
+ q (`str | None`, optional):
+ A keyword filtering the cards. When ``None`` the whole
+ catalog is browsed.
+ cursor (`str | None`, optional):
+ The opaque cursor from a previous page. When ``None`` the
+ first page is returned.
+ limit (`int`, defaults to `20`):
+ The maximum number of cards per page.
+
+ Returns:
+ `SkillHubPage`:
+ The requested page of cards plus the next cursor.
+ """
+
+ @abstractmethod
+ async def get_skill(
+ self,
+ user_id: str,
+ card_id: str,
+ ) -> SkillCard:
+ """Fetch a single card by its hub-local id, with ``SKILL.md``.
+
+ Args:
+ user_id (`str`):
+ The user identifier to query the card for.
+ card_id (`str`):
+ The :attr:`SkillCard.id` addressing the card on this hub.
+
+ Returns:
+ `SkillCard`:
+ The matching card with :attr:`SkillCard.markdown` set.
+
+ Raises:
+ `KeyError`:
+ When this hub has no card under ``card_id``.
+ """
+
+ @abstractmethod
+ async def download(
+ self,
+ user_id: str,
+ card_id: str,
+ version: str | None = None,
+ ) -> SkillArchive:
+ """Open the skill archive for streaming.
+
+ Returns rather than yields so the format is known before the
+ first byte, and so the caller can pipe the stream onward
+ without ever holding the archive.
+
+ Takes ``user_id`` for the same reason the read methods do: a hub
+ that hides cards from a user must be able to refuse the download
+ too, otherwise guessing a card id bypasses the filter.
+
+ Args:
+ user_id (`str`):
+ The user identifier the download is authorized against.
+ card_id (`str`):
+ The :attr:`SkillCard.id` addressing the card on this hub.
+ version (`str | None`, optional):
+ A specific version to download. When ``None`` the latest
+ version is used.
+
+ Returns:
+ `SkillArchive`:
+ The archive format and its byte stream.
+
+ Raises:
+ `KeyError`:
+ When this hub has no card under ``card_id``.
+ """
diff --git a/src/agentscope/app/hub/_skill/_card.py b/src/agentscope/app/hub/_skill/_card.py
new file mode 100644
index 000000000..5b74a9f21
--- /dev/null
+++ b/src/agentscope/app/hub/_skill/_card.py
@@ -0,0 +1,152 @@
+# -*- coding: utf-8 -*-
+"""The skill card models."""
+from typing import Self
+
+from pydantic import BaseModel, Field, model_validator
+
+
+class SkillCard(BaseModel):
+ """A single skill listing on a hub.
+
+ Unlike an :class:`MCPCard` there is nothing to configure: installing
+ a skill copies its files into the workspace, so no input form and no
+ template substitution are involved.
+
+ :attr:`id` addresses the card on its hub — together with
+ :attr:`hub_id` it names the card globally; :attr:`name` is the
+ skill's own name.
+ """
+
+ hub_id: str = Field(
+ title="Hub ID",
+ description="The id of the hub this card came from.",
+ )
+
+ id: str = Field(
+ default="",
+ title="ID",
+ description=(
+ "The identifier addressing this card on its hub. Defaults to "
+ "``name`` for registries that expose no separate id."
+ ),
+ )
+
+ name: str = Field(
+ title="Name",
+ description="The skill name.",
+ )
+
+ description: str = Field(
+ default="",
+ title="Description",
+ description="The user-facing description of the skill.",
+ )
+
+ display_name: str | None = Field(
+ default=None,
+ title="Display Name",
+ description="The user-facing name, falling back to ``name``.",
+ )
+
+ tags: list[str] = Field(
+ default_factory=list,
+ title="Tags",
+ description="The tags categorizing this card.",
+ )
+
+ version: str | None = Field(
+ default=None,
+ title="Version",
+ description="The card version reported by the hub.",
+ )
+
+ updated_at: float | None = Field(
+ default=None,
+ title="Updated At",
+ description="The last-updated timestamp (Unix epoch seconds).",
+ )
+
+ author: str | None = Field(
+ default=None,
+ title="Author",
+ description="Who published the skill, when the hub says.",
+ )
+
+ icon_url: str | None = Field(
+ default=None,
+ title="Icon URL",
+ description=(
+ "An image representing the skill, for the card and the "
+ "detail view. ``None`` when the hub offers none — the UI is "
+ "expected to fall back rather than show a broken image."
+ ),
+ )
+
+ installs: int | None = Field(
+ default=None,
+ title="Installs",
+ description=(
+ "How many times this skill has been installed. ``None`` when "
+ "the hub does not count installs, which is not the same as "
+ "zero — render it only when set."
+ ),
+ )
+
+ downloads: int | None = Field(
+ default=None,
+ title="Downloads",
+ description=(
+ "How many times this skill has been downloaded. ``None`` "
+ "when the hub does not count downloads."
+ ),
+ )
+
+ url: str | None = Field(
+ default=None,
+ title="URL",
+ description=(
+ "The skill's page on the hub's website, for a 'view on the "
+ "hub' link. ``None`` when the hub has no web presence."
+ ),
+ )
+
+ markdown: str | None = Field(
+ default=None,
+ title="Markdown",
+ description=(
+ "The ``SKILL.md`` body. Left ``None`` when browsing so the "
+ "catalog does not fetch one file per card; populated by "
+ "``get_skill``."
+ ),
+ )
+
+ metadata: dict = Field(
+ default_factory=dict,
+ title="Metadata",
+ description="The hub-specific extra fields carried verbatim.",
+ )
+
+ @model_validator(mode="after")
+ def _default_id_to_name(self) -> Self:
+ """Fall back to ``name`` when the hub exposes no separate id."""
+ if not self.id:
+ self.id = self.name
+ return self
+
+
+class SkillHubPage(BaseModel):
+ """One page of skill cards."""
+
+ cards: list[SkillCard] = Field(
+ title="Cards",
+ description="The cards on this page.",
+ )
+
+ next_cursor: str | None = Field(
+ default=None,
+ title="Next Cursor",
+ description=(
+ "The opaque cursor fetching the following page, or ``None`` "
+ "when this is the last one."
+ ),
+ )
diff --git a/src/agentscope/app/hub/_skill/_claw_hub.py b/src/agentscope/app/hub/_skill/_claw_hub.py
new file mode 100644
index 000000000..d8ea5b0e5
--- /dev/null
+++ b/src/agentscope/app/hub/_skill/_claw_hub.py
@@ -0,0 +1,579 @@
+# -*- coding: utf-8 -*-
+"""The ClawHub skill provider.
+
+A thin async client around the ClawHub HTTP API (``https://clawhub.ai``)
+that exposes the registry skills through the
+:class:`~agentscope.app.hub._skill._base.SkillHubBase` interface.
+
+`ClawHub HTTP API <https://clawhub.ai/api/v1/openapi.json>`_
+
+.. note:: Only the public read endpoints are required. A Bearer token
+ (``clh_...``) is optional and, when provided, raises the per-user
+ rate limit.
+
+.. note:: Browsing and searching are different upstream endpoints:
+ ``GET /api/v1/skills`` is cursor-paginated but takes no query, while
+ ``GET /api/v1/search`` takes a query but returns a single page.
+"""
+import asyncio
+import random
+import re
+from datetime import datetime
+from contextlib import AsyncExitStack
+from typing import TYPE_CHECKING, Any, AsyncIterator
+
+from ._base import SkillArchive, SkillHubBase
+from .._error import HubError
+from ._card import SkillCard, SkillHubPage
+
+if TYPE_CHECKING:
+ import httpx
+
+DEFAULT_BASE_URL = "https://clawhub.ai"
+
+# The default streaming chunk size (64 KiB) used when downloading skill
+# archives, balancing memory usage and per-chunk overhead.
+DEFAULT_CHUNK_SIZE = 64 * 1024
+
+# ClawHub's bulk skill generator stamps versions as ``0.<date>.<time>``
+# rather than semver, e.g. ``0.20260729.110214``. Shown raw that is 17
+# characters of noise next to a skill name, so it is rendered as the
+# date it encodes.
+_TIMESTAMP_VERSION = re.compile(r"^0\.(\d{8})\.(\d{6})$")
+
+
+def _humanize_version(version: str | None) -> str | None:
+ """Render a timestamp-style version as its date.
+
+ Anything else — semver included — is returned untouched, so a hub
+ that versions its skills properly is never rewritten.
+
+ Args:
+ version (`str | None`):
+ The version as reported upstream.
+
+ Returns:
+ `str | None`:
+ ``YYYY-MM-DD`` for a timestamp version, else the input.
+ """
+ if version is None:
+ return None
+
+ match = _TIMESTAMP_VERSION.match(version)
+ if not match:
+ return version
+
+ try:
+ stamp = datetime.strptime(match.group(1), "%Y%m%d")
+ except ValueError:
+ # Eight digits that are not a real date — leave it alone.
+ return version
+ return stamp.strftime("%Y-%m-%d")
+
+
+class ClawSkillHub(SkillHubBase):
+ """A skill hub backed by the ClawHub registry.
+
+ .. code-block:: python
+
+ hub = ClawSkillHub(api_token="clh_xxx")
+ page = await hub.list_skills(user_id="alice", q="git")
+ async for chunk in hub.download("gifgrep"):
+ ... # stream-write into a sandbox
+ """
+
+ def __init__(
+ self,
+ hub_id: str = "clawhub",
+ display_name: str = "ClawHub",
+ description: str = "The ClawHub public skill registry.",
+ icon_url: str | None = "https://openclaw.ai/favicon.svg",
+ *,
+ base_url: str = DEFAULT_BASE_URL,
+ api_token: str | None = None,
+ timeout: float = 30.0,
+ max_retries: int = 3,
+ ) -> None:
+ """Initialize the ClawHub skill provider.
+
+ Args:
+ hub_id (`str`, defaults to `"clawhub"`):
+ The stable identifier addressing this hub in the API
+ routes.
+ display_name (`str`, defaults to `"ClawHub"`):
+ The user-facing hub name.
+ description (`str`, optional):
+ The user-facing hub description.
+ icon_url (`str | None`, optional):
+ The hub's icon, defaulting to the ClawHub favicon.
+ base_url (`str`, defaults to `"https://clawhub.ai"`):
+ The base URL of the ClawHub registry.
+ api_token (`str | None`, optional):
+ The ClawHub Bearer token (``clh_...``). When provided,
+ requests are authenticated and use the higher per-user
+ rate limit bucket.
+ timeout (`float`, defaults to `30.0`):
+ The per-request timeout in seconds.
+ max_retries (`int`, defaults to `3`):
+ The maximum number of retries when a request is rate
+ limited (HTTP ``429``).
+ """
+ super().__init__(hub_id, display_name, description, icon_url)
+ self.base_url = base_url.rstrip("/")
+ self.api_token = api_token
+ self.timeout = timeout
+ self.max_retries = max_retries
+ self._client: "httpx.AsyncClient | None" = None
+
+ async def __aenter__(self) -> "ClawSkillHub":
+ """Open the HTTP client shared by every request.
+
+ Returns:
+ `ClawSkillHub`:
+ ``self``.
+ """
+ import httpx
+
+ self._client = httpx.AsyncClient(timeout=self.timeout)
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ """Close the shared HTTP client."""
+ if self._client is not None:
+ await self._client.aclose()
+ self._client = None
+
+ def _http(self) -> "httpx.AsyncClient":
+ """Return the shared client, opening one if the hub was never
+ entered — which is how a hub used outside the app behaves.
+
+ Returns:
+ `httpx.AsyncClient`:
+ The client to issue requests with.
+ """
+ import httpx
+
+ if self._client is None:
+ self._client = httpx.AsyncClient(timeout=self.timeout)
+ return self._client
+
+ def _headers(self) -> dict[str, str]:
+ """Build the request headers, including auth when available.
+
+ Returns:
+ `dict[str, str]`:
+ The HTTP headers to attach to a request.
+ """
+ headers = {"Accept": "application/json"}
+ if self.api_token:
+ headers["Authorization"] = f"Bearer {self.api_token}"
+ return headers
+
+ @staticmethod
+ def _retry_delay(headers: dict) -> float:
+ """Compute the retry delay (in seconds) from rate-limit headers.
+
+ Honors ``Retry-After`` first, then falls back to
+ ``RateLimit-Reset`` (delay) and ``X-RateLimit-Reset`` (absolute
+ Unix epoch seconds), as documented by ClawHub.
+
+ Args:
+ headers (`dict`):
+ The response headers from a ``429`` response.
+
+ Returns:
+ `float`:
+ The number of seconds to wait before retrying.
+ """
+ import time
+
+ retry_after = headers.get("Retry-After") or headers.get(
+ "retry-after",
+ )
+ if retry_after:
+ try:
+ return max(0.0, float(retry_after))
+ except ValueError:
+ pass
+
+ reset = headers.get("RateLimit-Reset") or headers.get(
+ "ratelimit-reset",
+ )
+ if reset:
+ try:
+ return max(0.0, float(reset))
+ except ValueError:
+ pass
+
+ x_reset = headers.get("X-RateLimit-Reset") or headers.get(
+ "x-ratelimit-reset",
+ )
+ if x_reset:
+ try:
+ return max(0.0, float(x_reset) - time.time())
+ except ValueError:
+ pass
+
+ return 1.0
+
+ async def _request(
+ self,
+ method: str,
+ path: str,
+ params: dict | None = None,
+ ) -> "httpx.Response":
+ """Send a request to the ClawHub API with rate-limit handling.
+
+ Args:
+ method (`str`):
+ The HTTP method, e.g. ``"GET"``.
+ path (`str`):
+ The request path under :attr:`base_url`, e.g.
+ ``"/api/v1/skills/gifgrep"``.
+ params (`dict | None`, optional):
+ The query parameters to attach to the request.
+
+ Returns:
+ `httpx.Response`:
+ The successful HTTP response.
+
+ Raises:
+ `HubError`:
+ When the API returns a non-success status code.
+ """
+ url = f"{self.base_url}{path}"
+ client = self._http()
+ for attempt in range(self.max_retries + 1):
+ response = await client.request(
+ method,
+ url,
+ params=params,
+ headers=self._headers(),
+ )
+
+ if response.status_code == 429 and attempt < self.max_retries:
+ # Wait with jittered backoff to avoid synchronized
+ # retries, as recommended by ClawHub.
+ delay = self._retry_delay(response.headers)
+ await asyncio.sleep(delay + random.uniform(0, 1))
+ continue
+
+ if response.status_code >= 400:
+ raise HubError(
+ self.hub_id,
+ response.status_code,
+ response.text,
+ )
+
+ return response
+
+ raise HubError(
+ self.hub_id,
+ 429,
+ "Rate limit exceeded after retries",
+ )
+
+ async def download(
+ self,
+ user_id: str,
+ card_id: str,
+ version: str | None = None,
+ tag: str | None = None,
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
+ ) -> SkillArchive:
+ """Open a skill archive via ``GET /api/v1/download``.
+
+ The response headers are awaited here — so a missing skill or an
+ exhausted rate limit raises before the caller commits to an
+ install — while the body stays lazy, letting the archive be
+ piped into a sandbox without ever being held whole.
+
+ Args:
+ user_id (`str`):
+ The user identifier the download is authorized against.
+ Unused by the public ClawHub catalog, kept for interface
+ compatibility.
+ card_id (`str`):
+ The canonical slug of the skill.
+ version (`str | None`, optional):
+ A specific semver version to download. When omitted with
+ ``tag``, the latest version is used.
+ tag (`str | None`, optional):
+ A tag name (e.g. ``"latest"``) to resolve the version.
+ chunk_size (`int`, defaults to `65536`):
+ The number of bytes to yield per chunk.
+
+ Returns:
+ `SkillArchive`:
+ The ZIP archive and its byte stream.
+
+ Raises:
+ `KeyError`:
+ When the registry has no skill under ``card_id``.
+ `HubError`:
+ When the API returns any other non-success status code.
+ """
+ params: dict = {"slug": card_id}
+ if version is not None:
+ params["version"] = version
+ if tag is not None:
+ params["tag"] = tag
+
+ url = f"{self.base_url}/api/v1/download"
+ client = self._http()
+ # Only the response is owned here — the client outlives every
+ # download, so closing it would break the next one.
+ stack = AsyncExitStack()
+ try:
+ for attempt in range(self.max_retries + 1):
+ response = await stack.enter_async_context(
+ client.stream(
+ "GET",
+ url,
+ params=params,
+ headers=self._headers(),
+ ),
+ )
+ if response.status_code == 429 and attempt < self.max_retries:
+ # Wait with jittered backoff before re-opening the
+ # stream, as recommended by ClawHub.
+ delay = self._retry_delay(response.headers)
+ await stack.aclose()
+ stack = AsyncExitStack()
+ await asyncio.sleep(delay + random.uniform(0, 1))
+ continue
+
+ if response.status_code >= 400:
+ # Read the (plain-text) error body before the stream
+ # context closes.
+ body = await response.aread()
+ if response.status_code == 404:
+ raise KeyError(card_id)
+ raise HubError(
+ self.hub_id,
+ response.status_code,
+ body.decode("utf-8", errors="replace"),
+ )
+
+ return SkillArchive(
+ "zip",
+ self._drain(stack, response, chunk_size),
+ )
+
+ raise HubError(
+ self.hub_id,
+ 429,
+ "Rate limit exceeded after retries",
+ )
+ except BaseException:
+ await stack.aclose()
+ raise
+
+ @staticmethod
+ async def _drain(
+ stack: AsyncExitStack,
+ response: "httpx.Response",
+ chunk_size: int,
+ ) -> AsyncIterator[bytes]:
+ """Yield the response body, closing the response after.
+
+ Args:
+ stack (`AsyncExitStack`):
+ Holds the open response, closed when the body is done.
+ response (`httpx.Response`):
+ The open response whose body is drained.
+ chunk_size (`int`):
+ The number of bytes to yield per chunk.
+
+ Yields:
+ `bytes`:
+ The next chunk of the archive.
+ """
+ try:
+ async for chunk in response.aiter_bytes(chunk_size):
+ yield chunk
+ finally:
+ await stack.aclose()
+
+ def _to_card(self, item: dict) -> SkillCard:
+ """Build a :class:`SkillCard` from one catalog or search record.
+
+ No per-card request is made: everything comes from the record the
+ listing already returned, which is what keeps browsing at one
+ upstream call per page.
+
+ The slug is used as the card id — it is what every lookup and
+ download endpoint takes. The opaque ``id`` the search endpoint
+ also returns cannot be resolved back through the public API, so
+ it is deliberately ignored.
+
+ Args:
+ item (`dict`):
+ A record from ``GET /api/v1/skills`` (``items``) or
+ ``GET /api/v1/search`` (``results``).
+
+ Returns:
+ `SkillCard`:
+ The card describing this skill.
+ """
+ # ``latestVersion`` is an object on the catalog endpoint and
+ # absent on the search endpoint, which carries ``version``.
+ latest = item.get("latestVersion")
+ if isinstance(latest, dict):
+ version = latest.get("version")
+ else:
+ version = latest or item.get("version")
+
+ updated_at = item.get("updatedAt")
+
+ stats = (
+ item.get("stats") if isinstance(item.get("stats"), dict) else {}
+ )
+
+ # The owner sits beside the skill on the detail endpoint and under
+ # ``native`` on search; the catalog endpoint omits it entirely, so
+ # most browse cards carry no author and no icon.
+ owner = item.get("owner") or (item.get("native") or {}).get("owner")
+ owner = owner if isinstance(owner, dict) else {}
+
+ # The search endpoint hands back an owner-scoped canonical path;
+ # the catalog endpoint has no link at all, so the slug route is
+ # built instead — it 307s to the same canonical page.
+ canonical = item.get("canonicalUrl")
+ url = (
+ f"{self.base_url}{canonical}"
+ if canonical
+ else f"{self.base_url}/skills/{item['slug']}"
+ )
+
+ return SkillCard(
+ hub_id=self.hub_id,
+ id=item["slug"],
+ name=item["slug"],
+ display_name=item.get("displayName"),
+ description=item.get("summary") or "",
+ # ``topics`` holds the categorical labels. Upstream ``tags``
+ # is a version-tag -> version map, not something to show.
+ tags=list(item.get("topics") or []),
+ version=_humanize_version(version),
+ # ``updatedAt`` is reported in Unix milliseconds.
+ updated_at=float(updated_at) / 1000.0 if updated_at else None,
+ author=owner.get("displayName") or owner.get("handle"),
+ icon_url=owner.get("image"),
+ installs=stats.get("installs"),
+ # Nested under ``stats`` on the catalog, top level on search.
+ downloads=stats.get("downloads", item.get("downloads")),
+ url=url,
+ metadata={
+ key: item[key]
+ for key in ("stats", "downloads", "tags")
+ if item.get(key)
+ },
+ )
+
+ async def list_skills(
+ self,
+ user_id: str,
+ q: str | None = None,
+ cursor: str | None = None,
+ limit: int = 20,
+ ) -> SkillHubPage:
+ """Browse or search the ClawHub registry in one request.
+
+ With ``q`` the search endpoint is used, which ranks by relevance
+ but returns a single page — ``next_cursor`` is then always
+ ``None``. Without ``q`` the cursor-paginated catalog is browsed.
+
+ Args:
+ user_id (`str`):
+ The user identifier to query skill cards for. Unused by
+ the public ClawHub catalog, kept for interface
+ compatibility.
+ q (`str | None`, optional):
+ A keyword filtering the cards.
+ cursor (`str | None`, optional):
+ The opaque cursor from a previous page. Ignored when
+ ``q`` is given, since search is not paginated upstream.
+ limit (`int`, defaults to `20`):
+ The maximum number of cards per page (1-200).
+
+ Returns:
+ `SkillHubPage`:
+ The requested page of cards plus the next cursor.
+
+ Raises:
+ `HubError`:
+ When the API returns a non-success status code.
+ """
+ if q:
+ response = await self._request(
+ "GET",
+ "/api/v1/search",
+ {"q": q, "limit": limit},
+ )
+ records = response.json().get("results") or []
+ next_cursor = None
+ else:
+ params: dict = {"limit": limit}
+ if cursor is not None:
+ params["cursor"] = cursor
+ response = await self._request("GET", "/api/v1/skills", params)
+ payload = response.json()
+ records = payload.get("items") or []
+ next_cursor = payload.get("nextCursor")
+
+ return SkillHubPage(
+ cards=[self._to_card(r) for r in records if r.get("slug")],
+ next_cursor=next_cursor,
+ )
+
+ async def get_skill(self, user_id: str, card_id: str) -> SkillCard:
+ """Fetch one skill plus its ``SKILL.md`` body.
+
+ Args:
+ user_id (`str`):
+ The user identifier to query the card for. Unused by the
+ public ClawHub catalog, kept for interface compatibility.
+ card_id (`str`):
+ The canonical slug of the skill.
+
+ Returns:
+ `SkillCard`:
+ The card with :attr:`SkillCard.markdown` populated.
+
+ Raises:
+ `KeyError`:
+ When the registry has no skill under ``card_id``.
+ `HubError`:
+ When the API returns any other non-success status code.
+ """
+ import frontmatter
+
+ try:
+ detail, markdown = await asyncio.gather(
+ self._request("GET", f"/api/v1/skills/{card_id}"),
+ self._request(
+ "GET",
+ f"/api/v1/skills/{card_id}/file",
+ {"path": "SKILL.md"},
+ ),
+ )
+ except HubError as e:
+ if e.status_code == 404:
+ raise KeyError(card_id) from e
+ raise
+
+ payload = detail.json()
+ item = dict(payload.get("skill") or {})
+ item.setdefault("slug", card_id)
+ item["latestVersion"] = payload.get("latestVersion")
+ # The owner is a sibling of ``skill`` here, but ``_to_card`` reads
+ # it off the record, so fold it in.
+ item["owner"] = payload.get("owner")
+
+ card = self._to_card(item)
+ parsed = await asyncio.to_thread(frontmatter.loads, markdown.text)
+ card.markdown = parsed.content
+ if not card.description:
+ card.description = str(parsed.get("description", ""))
+ return card
diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.py
index 6bc2eb54f..e05f9f457 100644
--- a/src/agentscope/app/storage/__init__.py
+++ b/src/agentscope/app/storage/__init__.py
@@ -13,6 +13,7 @@ from ._model import (
KnowledgeDocumentData,
KnowledgeDocumentRecord,
KnowledgeDocumentStatus,
+ MCPRecord,
ScheduleData,
ScheduleRecord,
ScheduleSource,
@@ -20,6 +21,7 @@ from ._model import (
SessionKnowledgeConfig,
SessionRecord,
SessionSource,
+ SkillRecord,
ChatModelConfig,
TTSModelConfig,
EmbeddingModelConfig,
@@ -71,10 +73,12 @@ __all__ = [
"KnowledgeDocumentData",
"KnowledgeDocumentRecord",
"KnowledgeDocumentStatus",
+ "MCPRecord",
"SessionConfig",
"SessionKnowledgeConfig",
"SessionRecord",
"SessionSource",
+ "SkillRecord",
"ChatModelConfig",
"TTSModelConfig",
"EmbeddingModelConfig",
diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.py
index 63e7fa433..c99ab28cc 100644
--- a/src/agentscope/app/storage/_base.py
+++ b/src/agentscope/app/storage/_base.py
@@ -12,10 +12,12 @@ from ._model import (
KnowledgeBaseRecord,
KnowledgeDocumentRecord,
KnowledgeDocumentStatus,
+ MCPRecord,
ScheduleRecord,
SessionRecord,
SessionConfig,
SessionSource,
+ SkillRecord,
TeamRecord,
)
from ...credential import CredentialBase
@@ -109,6 +111,193 @@ class StorageBase(ABC):
True if deleted, False if not found.
"""
+ @abstractmethod
+ async def upsert_mcp(self, user_id: str, mcp_record: MCPRecord) -> str:
+ """Create or update an installed-MCP record.
+
+ The record's ``client.name`` is unique per user — the workspace
+ relation is derived by joining on it — so writing a name another
+ record already holds is an error rather than an overwrite.
+
+ Args:
+ user_id (`str`):
+ The user id.
+ mcp_record (`MCPRecord`):
+ The record to write. Its ``id`` decides create vs update.
+
+ Returns:
+ `str`:
+ The MCP record id.
+
+ Raises:
+ `ValueError`:
+ When another record of this user already uses the name.
+ """
+
+ @abstractmethod
+ async def list_mcps(self, user_id: str) -> list[MCPRecord]:
+ """List every MCP a user has installed, enabled or not.
+
+ Args:
+ user_id (`str`):
+ The user id.
+
+ Returns:
+ `list[MCPRecord]`:
+ All installed-MCP records for the user.
+ """
+
+ @abstractmethod
+ async def get_mcp(self, user_id: str, mcp_id: str) -> MCPRecord | None:
+ """Fetch a single installed-MCP record by id.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ mcp_id (`str`):
+ The record id.
+
+ Returns:
+ `MCPRecord | None`:
+ The record, or ``None`` if not found.
+ """
+
+ @abstractmethod
+ async def get_mcp_by_name(
+ self,
+ user_id: str,
+ name: str,
+ ) -> MCPRecord | None:
+ """Fetch an installed-MCP record by its MCP name.
+
+ This is the lookup the workspace relation is derived through —
+ a workspace holds names, not record ids.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ name (`str`):
+ The MCP name, i.e. ``record.client.name``.
+
+ Returns:
+ `MCPRecord | None`:
+ The record, or ``None`` if the user has no MCP so named.
+ """
+
+ @abstractmethod
+ async def delete_mcp(self, user_id: str, mcp_id: str) -> bool:
+ """Delete an installed-MCP record.
+
+ Args:
+ user_id (`str`):
+ The user id.
+ mcp_id (`str`):
+ The record id.
+
+ Returns:
+ `bool`:
+ True if deleted, False if not found.
+ """
+
+ @abstractmethod
+ async def upsert_skill(
+ self,
+ user_id: str,
+ skill_record: SkillRecord,
+ ) -> str:
+ """Create or update an installed-skill record.
+
+ The record's ``name`` is unique per user, for the same reason
+ MCP names are: a workspace refers to a skill by name.
+
+ Args:
+ user_id (`str`):
+ The user id.
+ skill_record (`SkillRecord`):
+ The record to write. Its ``id`` decides create vs update.
+
+ Returns:
+ `str`:
+ The skill record id.
+
+ Raises:
+ `ValueError`:
+ When another record of this user already uses the name.
+ """
+
+ @abstractmethod
+ async def list_skills(self, user_id: str) -> list[SkillRecord]:
+ """List every skill a user has installed, enabled or not.
+
+ Named apart from the workspace's ``list_skills`` because these
+ are library records, not skills present in any workspace.
+
+ Args:
+ user_id (`str`):
+ The user id.
+
+ Returns:
+ `list[SkillRecord]`:
+ All installed-skill records for the user.
+ """
+
+ @abstractmethod
+ async def get_skill(
+ self,
+ user_id: str,
+ skill_id: str,
+ ) -> SkillRecord | None:
+ """Fetch a single installed-skill record by id.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ skill_id (`str`):
+ The record id.
+
+ Returns:
+ `SkillRecord | None`:
+ The record, or ``None`` if not found.
+ """
+
+ @abstractmethod
+ async def get_skill_by_name(
+ self,
+ user_id: str,
+ name: str,
+ ) -> SkillRecord | None:
+ """Fetch an installed-skill record by its skill name.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ name (`str`):
+ The skill name.
+
+ Returns:
+ `SkillRecord | None`:
+ The record, or ``None`` if the user has none so named.
+ """
+
+ @abstractmethod
+ async def delete_skill(
+ self,
+ user_id: str,
+ skill_id: str,
+ ) -> bool:
+ """Delete an installed-skill record.
+
+ Args:
+ user_id (`str`):
+ The user id.
+ skill_id (`str`):
+ The record id.
+
+ Returns:
+ `bool`:
+ True if deleted, False if not found.
+ """
+
@abstractmethod
async def upsert_agent(
self,
diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.py
index 9aac92b70..2ea1d6520 100644
--- a/src/agentscope/app/storage/_model/__init__.py
+++ b/src/agentscope/app/storage/_model/__init__.py
@@ -9,6 +9,7 @@ from ._knowledge_document import (
KnowledgeDocumentRecord,
KnowledgeDocumentStatus,
)
+from ._mcp import MCPRecord
from ._schedule import ScheduleData, ScheduleRecord, ScheduleSource
from ._session import (
SessionRecord,
@@ -19,6 +20,7 @@ from ._session import (
EmbeddingModelConfig,
SessionSource,
)
+from ._skill import SkillRecord
from ._team import TeamRecord, TeamData, TeamMember
from ._user import UserRecord
@@ -31,6 +33,7 @@ __all__ = [
"KnowledgeDocumentData",
"KnowledgeDocumentRecord",
"KnowledgeDocumentStatus",
+ "MCPRecord",
"ScheduleData",
"ScheduleRecord",
"ScheduleSource",
@@ -38,6 +41,7 @@ __all__ = [
"SessionKnowledgeConfig",
"SessionRecord",
"SessionSource",
+ "SkillRecord",
"ChatModelConfig",
"TTSModelConfig",
"EmbeddingModelConfig",
diff --git a/src/agentscope/app/storage/_model/_mcp.py b/src/agentscope/app/storage/_model/_mcp.py
new file mode 100644
index 000000000..bbe479289
--- /dev/null
+++ b/src/agentscope/app/storage/_model/_mcp.py
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+"""The installed-MCP record."""
+from pydantic import Field, computed_field
+
+from ._base import _RecordBase
+from ....mcp import MCPClient
+
+
+class MCPRecord(_RecordBase):
+ """One MCP a user has installed, at the user level rather than in any
+ one workspace.
+
+ This table is the *desired* state: a workspace's ``.mcp`` file is the
+ actual state, and the app converges the two. Every MCP a user owns
+ has a record here — installing from a hub and adding one by hand both
+ write one — because a workspace MCP with no record would be
+ indistinguishable from one the user removed.
+
+ The workspace relation is derived, not stored: it joins on the MCP
+ name, which is why :attr:`MCPClient.name` must be unique per user.
+ """
+
+ user_id: str
+
+ client: MCPClient
+ """The connectable instance, ready to hand to ``workspace.add_mcp``.
+ Its ``name`` is the user-unique handle the workspace joins on."""
+
+ # mypy cannot see through the decorator pair; the ignore is what
+ # pydantic's own docs prescribe for a computed property.
+ @computed_field # type: ignore[misc]
+ @property
+ def name(self) -> str:
+ """``client.name`` lifted to the top level so storage backends can
+ index it. Computed rather than stored, so it cannot go stale when
+ the client is renamed, and records written before it existed need
+ no migration."""
+ return self.client.name
+
+ display_name: str | None = Field(default=None)
+ """The card's user-facing name, snapshotted at install time."""
+
+ description: str = Field(default="")
+ """The card's description, snapshotted at install time."""
+
+ author: str | None = Field(default=None)
+ """Who published the MCP, snapshotted at install time."""
+
+ icon_url: str | None = Field(default=None)
+ """The card's icon, snapshotted at install time."""
+
+ url: str | None = Field(default=None)
+ """The MCP's page on the hub's website, snapshotted at install time."""
+
+ tags: list[str] = Field(default_factory=list)
+ """The card's tags, snapshotted at install time.
+
+ The display fields above are copied rather than looked up on read: an
+ MCP added by hand has no card to look up, and a hub that has gone
+ offline — or dropped the card — would otherwise leave the library
+ blank. The cost is that they go stale if the card changes upstream,
+ which the version check has to refresh anyway.
+ """
+
+ values: dict = Field(default_factory=dict)
+ """The answers the user gave the card's ``inputs_schema``, e.g. API
+ keys.
+
+ Kept so the config can be re-rendered without the user retyping
+ everything — changing one key, or moving to a newer card version.
+ The secret is already in ``client.mcp_config`` in plaintext, so
+ holding it here too widens nothing; it is simply not projected onto
+ any response.
+ """
+
+ hub_id: str | None = Field(default=None)
+ """The hub this was installed from, or ``None`` when added by hand."""
+
+ card_id: str | None = Field(default=None)
+ """The card's id on that hub. Paired with ``hub_id`` it answers
+ "where did this come from" and "is there a newer version"."""
+
+ version: str | None = Field(default=None)
+ """The card version installed, as reported by the hub at the time."""
+
+ enabled: bool = Field(default=True)
+ """Whether the MCP should be present in the user's workspaces. A
+ disabled record is kept so re-enabling does not lose its config."""
diff --git a/src/agentscope/app/storage/_model/_skill.py b/src/agentscope/app/storage/_model/_skill.py
new file mode 100644
index 000000000..fc2c8e8d3
--- /dev/null
+++ b/src/agentscope/app/storage/_model/_skill.py
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+"""The installed-skill record."""
+from pydantic import Field
+
+from ._base import _RecordBase
+
+
+class SkillRecord(_RecordBase):
+ """One skill a user has installed, at the user level rather than in
+ any one workspace — the skill counterpart of :class:`MCPRecord`.
+
+ Unlike an MCP, whose whole substance is a config small enough to
+ store inline, a skill is a directory of files. Those files are *not*
+ kept here: the record holds where the skill came from and what it
+ says it does, and the archive is re-fetched from the hub when the
+ skill is actually put into a workspace.
+
+ TODO: store the archive so the library survives the hub dropping the
+ card or going offline. That needs a blob store, and the one this app
+ has is only wired up alongside ``knowledge_base_manager``.
+ """
+
+ user_id: str
+
+ name: str
+ """The skill name, unique for this user. This is the handle a
+ workspace refers to it by, matching how MCP names work."""
+
+ display_name: str | None = Field(default=None)
+ """The card's user-facing name, snapshotted at install time."""
+
+ description: str = Field(default="")
+ """The card's description, snapshotted at install time."""
+
+ tags: list[str] = Field(default_factory=list)
+ """The card's tags, snapshotted at install time."""
+
+ author: str | None = Field(default=None)
+ """Who published the skill, snapshotted at install time."""
+
+ icon_url: str | None = Field(default=None)
+ """The card's icon, snapshotted at install time. Kept so the library
+ looks like the hub listing it came from rather than losing its
+ identity the moment it is installed."""
+
+ url: str | None = Field(default=None)
+ """The skill's page on the hub's website, snapshotted at install
+ time, so the library can still link back to where it came from."""
+
+ markdown: str = Field(default="")
+ """The ``SKILL.md`` body, snapshotted at install time. Enough to show
+ the user what the skill does without going back to the hub."""
+
+ hub_id: str | None = Field(default=None)
+ """The hub this was installed from, or ``None`` when added by hand."""
+
+ card_id: str | None = Field(default=None)
+ """The card's id on that hub. Paired with ``hub_id`` it answers
+ "where did this come from" and "is there a newer version"."""
+
+ version: str | None = Field(default=None)
+ """The card version installed, as reported by the hub at the time."""
+
+ enabled: bool = Field(default=True)
+ """Whether the skill should be present in the user's workspaces."""
diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.py
index 44dfa29dc..e958177ed 100644
--- a/src/agentscope/app/storage/_redis_storage.py
+++ b/src/agentscope/app/storage/_redis_storage.py
@@ -15,10 +15,12 @@ from ._model import (
KnowledgeBaseRecord,
KnowledgeDocumentRecord,
KnowledgeDocumentStatus,
+ MCPRecord,
ScheduleRecord,
SessionRecord,
SessionConfig,
SessionSource,
+ SkillRecord,
TeamRecord,
)
from ._utils import _dump_with_secrets
@@ -61,10 +63,20 @@ class RedisStorage(StorageBase):
)
agent: str = "agentscope:user:{user_id}:agent:{agent_id}"
session: str = "agentscope:user:{user_id}:session:{session_id}"
+ mcp: str = "agentscope:user:{user_id}:mcp:{mcp_id}"
+ skill: str = "agentscope:user:{user_id}:skill:{skill_id}"
# Index keys (Redis Sets — store all IDs for a given scope)
credential_index: str = "agentscope:user:{user_id}:credentials"
agent_index: str = "agentscope:user:{user_id}:agents"
+ mcp_index: str = "agentscope:user:{user_id}:mcps"
+ skill_index: str = "agentscope:user:{user_id}:skills"
+
+ # Name indexes (Redis Hash — name → record id). Each doubles as
+ # the per-user uniqueness constraint and as the lookup for the
+ # workspace relation, which joins on name rather than record id.
+ mcp_name_index: str = "agentscope:user:{user_id}:mcp_names"
+ skill_name_index: str = "agentscope:user:{user_id}:skill_names"
session_index: str = (
"agentscope:user:{user_id}:agent:{agent_id}:sessions"
)
@@ -400,6 +412,285 @@ class RedisStorage(StorageBase):
await self._client.srem(index_key, credential_id)
return deleted > 0
+ async def upsert_mcp(self, user_id: str, mcp_record: MCPRecord) -> str:
+ """Create or update an installed-MCP record for the given user.
+
+ Keeps the name index in step with the write: the name is claimed
+ for this record, and a rename releases the old one. A name held
+ by a different record is rejected outright — the workspace
+ relation joins on name, so two records sharing one would make
+ that join ambiguous.
+
+ Args:
+ user_id (`str`): The owner user id.
+ mcp_record (`MCPRecord`): The record to write.
+
+ Returns:
+ `str`: The id of the created or updated record.
+
+ Raises:
+ `ValueError`: When another record already uses the name.
+ """
+ name_key = self._key(
+ self.key_config.mcp_name_index,
+ user_id=user_id,
+ )
+ holder = await self._client.hget(name_key, mcp_record.client.name)
+ if holder is not None and holder != mcp_record.id:
+ raise ValueError(
+ f"An MCP named {mcp_record.client.name!r} already exists "
+ f"for this user.",
+ )
+
+ key = self._key(
+ self.key_config.mcp,
+ user_id=user_id,
+ mcp_id=mcp_record.id,
+ )
+ raw = await self._client.get(key)
+
+ mcp_record.user_id = user_id
+ if raw:
+ mcp_record.updated_at = datetime.now()
+
+ await self._set_with_ttl(key, mcp_record.model_dump_json())
+ await self._client.sadd(
+ self._key(self.key_config.mcp_index, user_id=user_id),
+ mcp_record.id,
+ )
+ await self._client.hset(
+ name_key,
+ mcp_record.client.name,
+ mcp_record.id,
+ )
+
+ if raw:
+ previous = MCPRecord.model_validate_json(raw).client.name
+ if previous != mcp_record.client.name:
+ await self._client.hdel(name_key, previous)
+
+ return mcp_record.id
+
+ async def list_mcps(self, user_id: str) -> list[MCPRecord]:
+ """Return every installed-MCP record belonging to the user.
+
+ Args:
+ user_id (`str`): The owner user id.
+
+ Returns:
+ `list[MCPRecord]`: All installed-MCP records for the user.
+ """
+ index_key = self._key(self.key_config.mcp_index, user_id=user_id)
+ ids = await self._client.smembers(index_key)
+ records = []
+ for mcp_id in ids:
+ raw = await self._client.get(
+ self._key(
+ self.key_config.mcp,
+ user_id=user_id,
+ mcp_id=mcp_id,
+ ),
+ )
+ if raw:
+ records.append(MCPRecord.model_validate_json(raw))
+ return records
+
+ async def get_mcp(self, user_id: str, mcp_id: str) -> MCPRecord | None:
+ """Fetch a single installed-MCP record by id."""
+ key = self._key(
+ self.key_config.mcp,
+ user_id=user_id,
+ mcp_id=mcp_id,
+ )
+ raw = await self._client.get(key)
+ return MCPRecord.model_validate_json(raw) if raw else None
+
+ async def get_mcp_by_name(
+ self,
+ user_id: str,
+ name: str,
+ ) -> MCPRecord | None:
+ """Fetch an installed-MCP record by its MCP name."""
+ mcp_id = await self._client.hget(
+ self._key(self.key_config.mcp_name_index, user_id=user_id),
+ name,
+ )
+ return await self.get_mcp(user_id, mcp_id) if mcp_id else None
+
+ async def delete_mcp(self, user_id: str, mcp_id: str) -> bool:
+ """Delete an installed-MCP record and drop it from both indexes.
+
+ Args:
+ user_id (`str`): The owner user id.
+ mcp_id (`str`): The id of the record to delete.
+
+ Returns:
+ `bool`: ``True`` if the record existed and was deleted.
+ """
+ record = await self.get_mcp(user_id, mcp_id)
+
+ deleted = await self._client.delete(
+ self._key(
+ self.key_config.mcp,
+ user_id=user_id,
+ mcp_id=mcp_id,
+ ),
+ )
+ await self._client.srem(
+ self._key(self.key_config.mcp_index, user_id=user_id),
+ mcp_id,
+ )
+ if record:
+ await self._client.hdel(
+ self._key(self.key_config.mcp_name_index, user_id=user_id),
+ record.client.name,
+ )
+ return deleted > 0
+
+ async def upsert_skill(
+ self,
+ user_id: str,
+ skill_record: SkillRecord,
+ ) -> str:
+ """Create or update an installed-skill record for the user.
+
+ Mirrors :meth:`upsert_mcp` — see it for the name-index rules.
+
+ Args:
+ user_id (`str`): The owner user id.
+ skill_record (`SkillRecord`): The record to write.
+
+ Returns:
+ `str`: The id of the created or updated record.
+
+ Raises:
+ `ValueError`: When another record already uses the name.
+ """
+ name_key = self._key(
+ self.key_config.skill_name_index,
+ user_id=user_id,
+ )
+ holder = await self._client.hget(name_key, skill_record.name)
+ if holder is not None and holder != skill_record.id:
+ raise ValueError(
+ f"A skill named {skill_record.name!r} already exists for "
+ f"this user.",
+ )
+
+ key = self._key(
+ self.key_config.skill,
+ user_id=user_id,
+ skill_id=skill_record.id,
+ )
+ raw = await self._client.get(key)
+
+ skill_record.user_id = user_id
+ if raw:
+ skill_record.updated_at = datetime.now()
+
+ await self._set_with_ttl(key, skill_record.model_dump_json())
+ await self._client.sadd(
+ self._key(self.key_config.skill_index, user_id=user_id),
+ skill_record.id,
+ )
+ await self._client.hset(name_key, skill_record.name, skill_record.id)
+
+ if raw:
+ previous = SkillRecord.model_validate_json(raw).name
+ if previous != skill_record.name:
+ await self._client.hdel(name_key, previous)
+
+ return skill_record.id
+
+ async def list_skills(self, user_id: str) -> list[SkillRecord]:
+ """Return every installed-skill record belonging to the user.
+
+ Args:
+ user_id (`str`): The owner user id.
+
+ Returns:
+ `list[SkillRecord]`: All installed-skill records for the user.
+ """
+ index_key = self._key(self.key_config.skill_index, user_id=user_id)
+ ids = await self._client.smembers(index_key)
+ records = []
+ for skill_id in ids:
+ raw = await self._client.get(
+ self._key(
+ self.key_config.skill,
+ user_id=user_id,
+ skill_id=skill_id,
+ ),
+ )
+ if raw:
+ records.append(SkillRecord.model_validate_json(raw))
+ return records
+
+ async def get_skill(
+ self,
+ user_id: str,
+ skill_id: str,
+ ) -> SkillRecord | None:
+ """Fetch a single installed-skill record by id."""
+ key = self._key(
+ self.key_config.skill,
+ user_id=user_id,
+ skill_id=skill_id,
+ )
+ raw = await self._client.get(key)
+ return SkillRecord.model_validate_json(raw) if raw else None
+
+ async def get_skill_by_name(
+ self,
+ user_id: str,
+ name: str,
+ ) -> SkillRecord | None:
+ """Fetch an installed-skill record by its skill name."""
+ skill_id = await self._client.hget(
+ self._key(self.key_config.skill_name_index, user_id=user_id),
+ name,
+ )
+ if not skill_id:
+ return None
+ return await self.get_skill(user_id, skill_id)
+
+ async def delete_skill(
+ self,
+ user_id: str,
+ skill_id: str,
+ ) -> bool:
+ """Delete an installed-skill record and drop both index entries.
+
+ Args:
+ user_id (`str`): The owner user id.
+ skill_id (`str`): The id of the record to delete.
+
+ Returns:
+ `bool`: ``True`` if the record existed and was deleted.
+ """
+ record = await self.get_skill(user_id, skill_id)
+
+ deleted = await self._client.delete(
+ self._key(
+ self.key_config.skill,
+ user_id=user_id,
+ skill_id=skill_id,
+ ),
+ )
+ await self._client.srem(
+ self._key(self.key_config.skill_index, user_id=user_id),
+ skill_id,
+ )
+ if record:
+ await self._client.hdel(
+ self._key(
+ self.key_config.skill_name_index,
+ user_id=user_id,
+ ),
+ record.name,
+ )
+ return deleted > 0
+
async def upsert_agent(
self,
user_id: str,
diff --git a/src/agentscope/app/storage/_sql/_alembic/versions/0002_mcps_skills.py b/src/agentscope/app/storage/_sql/_alembic/versions/0002_mcps_skills.py
new file mode 100644
index 000000000..79db0904d
--- /dev/null
+++ b/src/agentscope/app/storage/_sql/_alembic/versions/0002_mcps_skills.py
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+"""Installed-MCP and installed-skill tables.
+
+Revision ID: 0002_mcps_skills
+Revises: 0001_initial
+Create Date: 2026-08-01 09:34:28.407719
+
+Both tables are new, so there is nothing to backfill — the library has
+never been stored on SQL. ``(user_id, name)`` is unique on each because
+the workspace relation joins on the name.
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision: str = "0002_mcps_skills"
+down_revision: Union[str, None] = "0001_initial"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ """Create the ``mcps`` and ``skills`` tables."""
+ for table in ("mcps", "skills"):
+ op.create_table(
+ table,
+ sa.Column("user_id", sa.String(length=255), nullable=False),
+ sa.Column("name", sa.String(length=255), nullable=False),
+ sa.Column("id", sa.String(length=255), nullable=False),
+ sa.Column("created_at", sa.DateTime(), nullable=False),
+ sa.Column("updated_at", sa.DateTime(), nullable=False),
+ sa.Column("payload", sa.JSON(), nullable=False),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "user_id",
+ "name",
+ name=f"uq_{table}_user_name",
+ ),
+ )
+ with op.batch_alter_table(table, schema=None) as batch_op:
+ for column in ("created_at", "updated_at", "user_id"):
+ batch_op.create_index(
+ batch_op.f(f"ix_{table}_{column}"),
+ [column],
+ unique=False,
+ )
+
+
+def downgrade() -> None:
+ """Drop both tables created by :func:`upgrade`."""
+ for table in ("skills", "mcps"):
+ with op.batch_alter_table(table, schema=None) as batch_op:
+ for column in ("user_id", "updated_at", "created_at"):
+ batch_op.drop_index(batch_op.f(f"ix_{table}_{column}"))
+ op.drop_table(table)
diff --git a/src/agentscope/app/storage/_sql/_storage.py b/src/agentscope/app/storage/_sql/_storage.py
index 1cc558a12..381fa1b70 100644
--- a/src/agentscope/app/storage/_sql/_storage.py
+++ b/src/agentscope/app/storage/_sql/_storage.py
@@ -26,10 +26,12 @@ from .._model import (
KnowledgeBaseRecord,
KnowledgeDocumentRecord,
KnowledgeDocumentStatus,
+ MCPRecord,
ScheduleRecord,
SessionRecord,
SessionConfig,
SessionSource,
+ SkillRecord,
TeamRecord,
)
from .._utils import _dump_with_secrets
@@ -40,9 +42,11 @@ from ._tables import (
CredentialRow,
KnowledgeBaseRow,
KnowledgeDocumentRow,
+ MCPRow,
MessageRow,
ScheduleRow,
SessionRow,
+ SkillRow,
TeamRow,
)
from ....credential import CredentialBase
@@ -805,6 +809,171 @@ class AsyncSQLAlchemyStorage(StorageBase):
await sess.commit()
return result.rowcount > 0
+ # ------------------------------------------------------------------
+ # Installed MCPs and skills
+ #
+ # ``(user_id, name)`` is unique on both tables. The pre-write lookup
+ # below turns the common case into the same ``ValueError`` the Redis
+ # backend raises; the constraint is the backstop that closes the
+ # read-then-write window between concurrent writers.
+ # ------------------------------------------------------------------
+
+ async def upsert_mcp(self, user_id: str, mcp_record: MCPRecord) -> str:
+ """Create or update an installed-MCP record for *user_id*.
+
+ Same contract as :meth:`RedisStorage.upsert_mcp`.
+ """
+ holder = await self.get_mcp_by_name(user_id, mcp_record.name)
+ if holder is not None and holder.id != mcp_record.id:
+ raise ValueError(
+ f"An MCP named {mcp_record.name!r} already exists for "
+ f"this user.",
+ )
+ mcp_record.user_id = user_id
+ await self._write_row(MCPRow, mcp_record)
+ return mcp_record.id
+
+ async def list_mcps(self, user_id: str) -> list[MCPRecord]:
+ """Return every installed-MCP record for *user_id*."""
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ rows = (
+ (
+ await sess.execute(
+ select(MCPRow).where(MCPRow.user_id == user_id),
+ )
+ )
+ .scalars()
+ .all()
+ )
+ return [_to_record(r, MCPRecord) for r in rows]
+
+ async def get_mcp(self, user_id: str, mcp_id: str) -> MCPRecord | None:
+ """Fetch one installed-MCP record by id; owner-scoped."""
+ async with self._session() as sess:
+ row = await sess.get(MCPRow, mcp_id)
+ if row is None or row.user_id != user_id:
+ return None
+ return _to_record(row, MCPRecord)
+
+ async def get_mcp_by_name(
+ self,
+ user_id: str,
+ name: str,
+ ) -> MCPRecord | None:
+ """Fetch one installed-MCP record by its user-unique name."""
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ row = (
+ await sess.execute(
+ select(MCPRow).where(
+ MCPRow.user_id == user_id,
+ MCPRow.name == name,
+ ),
+ )
+ ).scalar_one_or_none()
+ return None if row is None else _to_record(row, MCPRecord)
+
+ async def delete_mcp(self, user_id: str, mcp_id: str) -> bool:
+ """Delete an installed-MCP record; owner-scoped."""
+ from sqlalchemy import delete
+
+ async with self._session() as sess:
+ result = await sess.execute(
+ delete(MCPRow).where(
+ MCPRow.id == mcp_id,
+ MCPRow.user_id == user_id,
+ ),
+ )
+ await sess.commit()
+ return result.rowcount > 0
+
+ async def upsert_skill(
+ self,
+ user_id: str,
+ skill_record: SkillRecord,
+ ) -> str:
+ """Create or update an installed-skill record for *user_id*.
+
+ Same contract as :meth:`RedisStorage.upsert_skill`.
+ """
+ holder = await self.get_skill_by_name(user_id, skill_record.name)
+ if holder is not None and holder.id != skill_record.id:
+ raise ValueError(
+ f"A skill named {skill_record.name!r} already exists for "
+ f"this user.",
+ )
+ skill_record.user_id = user_id
+ await self._write_row(SkillRow, skill_record)
+ return skill_record.id
+
+ async def list_skills(self, user_id: str) -> list[SkillRecord]:
+ """Return every installed-skill record for *user_id*."""
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ rows = (
+ (
+ await sess.execute(
+ select(SkillRow).where(SkillRow.user_id == user_id),
+ )
+ )
+ .scalars()
+ .all()
+ )
+ return [_to_record(r, SkillRecord) for r in rows]
+
+ async def get_skill(
+ self,
+ user_id: str,
+ skill_id: str,
+ ) -> SkillRecord | None:
+ """Fetch one installed-skill record by id; owner-scoped."""
+ async with self._session() as sess:
+ row = await sess.get(SkillRow, skill_id)
+ if row is None or row.user_id != user_id:
+ return None
+ return _to_record(row, SkillRecord)
+
+ async def get_skill_by_name(
+ self,
+ user_id: str,
+ name: str,
+ ) -> SkillRecord | None:
+ """Fetch one installed-skill record by its user-unique name."""
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ row = (
+ await sess.execute(
+ select(SkillRow).where(
+ SkillRow.user_id == user_id,
+ SkillRow.name == name,
+ ),
+ )
+ ).scalar_one_or_none()
+ return None if row is None else _to_record(row, SkillRecord)
+
+ async def delete_skill(
+ self,
+ user_id: str,
+ skill_id: str,
+ ) -> bool:
+ """Delete an installed-skill record; owner-scoped."""
+ from sqlalchemy import delete
+
+ async with self._session() as sess:
+ result = await sess.execute(
+ delete(SkillRow).where(
+ SkillRow.id == skill_id,
+ SkillRow.user_id == user_id,
+ ),
+ )
+ await sess.commit()
+ return result.rowcount > 0
+
# ------------------------------------------------------------------
# Agents
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/storage/_sql/_tables.py b/src/agentscope/app/storage/_sql/_tables.py
index 4daa99e36..9a37f0b4f 100644
--- a/src/agentscope/app/storage/_sql/_tables.py
+++ b/src/agentscope/app/storage/_sql/_tables.py
@@ -34,6 +34,7 @@ from sqlalchemy import (
ForeignKey,
Index,
String,
+ UniqueConstraint,
)
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
@@ -41,6 +42,9 @@ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
# Every id column is sized uniformly
_ID_LEN = 255
+# User-chosen names. Bounded because MySQL cannot index a TEXT column.
+_NAME_LEN = 255
+
class _Base(DeclarativeBase):
"""Declarative base shared by every table in :mod:`_sql`.
@@ -286,6 +290,51 @@ class KnowledgeDocumentRow(_JsonRecordMixin):
)
+class MCPRow(_JsonRecordMixin):
+ """One row per :class:`~agentscope.app.storage.MCPRecord`.
+
+ ``name`` is unique per user because the workspace relation joins on
+ it — two records sharing one would make that join ambiguous.
+ """
+
+ __tablename__ = "mcps"
+
+ user_id: Mapped[str] = mapped_column(
+ String(_ID_LEN),
+ nullable=False,
+ index=True,
+ )
+ name: Mapped[str] = mapped_column(String(_NAME_LEN), nullable=False)
+
+ __table_args__ = (
+ UniqueConstraint("user_id", "name", name="uq_mcps_user_name"),
+ )
+
+ _indexed_fields = ("user_id", "name")
+
+
+class SkillRow(_JsonRecordMixin):
+ """One row per :class:`~agentscope.app.storage.SkillRecord`.
+
+ Same ``(user_id, name)`` uniqueness as :class:`MCPRow`.
+ """
+
+ __tablename__ = "skills"
+
+ user_id: Mapped[str] = mapped_column(
+ String(_ID_LEN),
+ nullable=False,
+ index=True,
+ )
+ name: Mapped[str] = mapped_column(String(_NAME_LEN), nullable=False)
+
+ __table_args__ = (
+ UniqueConstraint("user_id", "name", name="uq_skills_user_name"),
+ )
+
+ _indexed_fields = ("user_id", "name")
+
+
class MessageRow(_Base):
"""One row per persisted :class:`~agentscope.message.Msg`.
diff --git a/src/agentscope/tool/_builtin/_backend.py b/src/agentscope/tool/_builtin/_backend.py
index a777312f3..aaa0a773e 100644
--- a/src/agentscope/tool/_builtin/_backend.py
+++ b/src/agentscope/tool/_builtin/_backend.py
@@ -42,7 +42,7 @@ import shutil
from abc import ABC, abstractmethod
from dataclasses import dataclass
from types import ModuleType
-from typing import Any
+from typing import Any, AsyncIterator
import aiofiles
@@ -308,6 +308,29 @@ class BackendBase(ABC):
The raw bytes to write.
"""
+ async def write_stream(
+ self,
+ path: str,
+ stream: AsyncIterator[bytes],
+ ) -> None:
+ """Write a byte stream to ``path``, creating parent directories.
+
+ The default buffers the whole stream and delegates to
+ :meth:`write_file`, so peak memory is the payload size; only
+ backends that override this (``LocalBackend``,
+ ``BubblewrapBackend``, ``K8sBackend``) are constant-memory.
+ Callers handling untrusted input must cap the payload
+ regardless.
+
+ Args:
+ path (`str`):
+ Destination path inside the backend's environment.
+ stream (`AsyncIterator[bytes]`):
+ The chunks to write, in order.
+ """
+ chunks = [chunk async for chunk in stream]
+ await self.write_file(path, b"".join(chunks))
+
# ── derived filesystem ops (shell-based defaults) ──────────────
async def getcwd(self) -> str:
@@ -634,6 +657,26 @@ class LocalBackend(BackendBase):
async with aiofiles.open(path, mode="wb") as f:
await f.write(data)
+ async def write_stream(
+ self,
+ path: str,
+ stream: AsyncIterator[bytes],
+ ) -> None:
+ """Write a byte stream to a local file, chunk by chunk.
+
+ Args:
+ path (`str`):
+ Destination path on the local filesystem.
+ stream (`AsyncIterator[bytes]`):
+ The chunks to write, in order.
+ """
+ parent = os.path.dirname(path)
+ if parent:
+ os.makedirs(parent, exist_ok=True)
+ async with aiofiles.open(path, mode="wb") as f:
+ async for chunk in stream:
+ await f.write(chunk)
+
async def getcwd(self) -> str:
"""Return the host process's current working directory.
diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.py
index 3747248f6..77d3bebfa 100644
--- a/src/agentscope/tool/_toolkit.py
+++ b/src/agentscope/tool/_toolkit.py
@@ -23,7 +23,7 @@ from ._base import ToolBase
from ._response import ToolResponse, ToolChunk
from ..skill import SkillLoaderBase, Skill
from ._types import RegisteredTool
-from .._utils._common import _json_loads_with_repair
+from .._utils._common import _describe_exception, _json_loads_with_repair
from ..exception import (
DeveloperOrientedException,
ToolNotFoundError,
@@ -517,8 +517,20 @@ class Toolkit:
# MCP tools
for client in group.mcps:
- tools = await client.list_tools()
- cache_tools.extend(tools)
+ try:
+ cache_tools.extend(await client.list_tools())
+ except Exception as e:
+ # One unreachable MCP must not take the reply down
+ # with it: an expired token or a server that is
+ # simply down would otherwise end the conversation
+ # rather than just withdraw that server's tools.
+ logger.warning(
+ "Skipping MCP '%s' in group '%s': listing its "
+ "tools failed with %s",
+ client.name,
+ group.name,
+ _describe_exception(e),
+ )
# Append cached tools into the available tools and solve the name
# conflict
diff --git a/src/agentscope/types/_reply.py b/src/agentscope/types/_reply.py
index e9e12e396..6b08dc4c2 100644
--- a/src/agentscope/types/_reply.py
+++ b/src/agentscope/types/_reply.py
@@ -36,6 +36,9 @@ class ErrorType(StrEnum):
"""Network error / timeout — no HTTP status available."""
INTERNAL = "internal"
"""Framework bug or otherwise unexpected exception."""
+ SETUP = "setup"
+ """The run failed before the agent replied at all — assembling the
+ agent, its toolkit, its knowledge bases, or resolving its model."""
UNKNOWN = "unknown"
"""Fallback when no better classification is possible."""
diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.py
index 305c950a1..86a173bad 100644
--- a/src/agentscope/workspace/_base.py
+++ b/src/agentscope/workspace/_base.py
@@ -56,7 +56,7 @@ import tarfile
from abc import abstractmethod
from copy import deepcopy
from pathlib import Path
-from typing import Self
+from typing import AsyncIterator, Literal, Self
from pydantic import AnyUrl
@@ -99,6 +99,48 @@ _EXTRACT_TAR_SHIM = (
"os.unlink(src)\n"
)
+#: Expands an archive inside the sandbox. Runs there rather than on the
+#: server so a traversing or bomb-sized archive detonates in the
+#: isolated environment. Argv: src, dst, format, max extracted bytes.
+_EXTRACT_ARCHIVE_SHIM = (
+ "import os, sys, tarfile, zipfile\n"
+ "src, dst, fmt, limit = sys.argv[1:5]\n"
+ "limit = int(limit)\n"
+ "os.makedirs(dst, exist_ok=True)\n"
+ "dst_real = os.path.realpath(dst)\n"
+ "def check(name):\n"
+ " target = os.path.realpath(os.path.join(dst, name))\n"
+ " if not (target == dst_real"
+ " or target.startswith(dst_real + os.sep)):\n"
+ " raise Exception('unsafe archive member: ' + name)\n"
+ "if fmt == 'zip':\n"
+ " ar = zipfile.ZipFile(src)\n"
+ " members = ar.infolist()\n"
+ " total = sum(m.file_size for m in members)\n"
+ " names = [m.filename for m in members]\n"
+ "else:\n"
+ " ar = tarfile.open(src)\n"
+ " members = ar.getmembers()\n"
+ " total = sum(m.size for m in members)\n"
+ " names = [m.name for m in members]\n"
+ " for m in members:\n"
+ " if m.issym() or m.islnk():\n"
+ " check(os.path.join(os.path.dirname(m.name), m.linkname))\n"
+ "try:\n"
+ " if total > limit:\n"
+ " raise Exception('archive expands to %d bytes, limit is %d'\n"
+ " % (total, limit))\n"
+ " for name in names:\n"
+ " check(name)\n"
+ " ar.extractall(dst, members)\n"
+ "finally:\n"
+ " ar.close()\n"
+ "os.unlink(src)\n"
+)
+
+#: Ceiling on what an archive may expand to inside the sandbox.
+DEFAULT_MAX_EXTRACTED_BYTES = 500 * 1024 * 1024
+
class WorkspaceBase:
"""Abstract base class for all workspace implementations.
@@ -687,6 +729,148 @@ class WorkspaceBase:
logger.info("Added skill %r at %s", dir_name, remote_dir)
+ async def add_skill_archive(
+ self,
+ stream: AsyncIterator[bytes],
+ fmt: Literal["zip", "tar", "tar.gz"],
+ dir_name: str,
+ max_extracted_bytes: int = DEFAULT_MAX_EXTRACTED_BYTES,
+ ) -> None:
+ """Install a skill from an archive stream into ``skills/``.
+
+ The archive is piped straight into the sandbox and expanded
+ there, so the server never holds it whole. Expansion lands in a
+ staging directory that is renamed into place only once it is
+ known to hold a ``SKILL.md`` — a failed install leaves nothing
+ behind.
+
+ Args:
+ stream (`AsyncIterator[bytes]`):
+ The archive bytes, in order.
+ fmt (`Literal["zip", "tar", "tar.gz"]`):
+ The archive format.
+ dir_name (`str`):
+ Directory name to install as. A numeric suffix is
+ appended when it is taken.
+ max_extracted_bytes (`int`):
+ Ceiling on the archive's expanded size.
+
+ Raises:
+ ValueError:
+ If ``dir_name`` is not a plain name, or the archive
+ holds no ``SKILL.md``.
+ RuntimeError:
+ If expanding the archive inside the sandbox fails.
+ """
+ if dir_name in (".", "..") or os.path.basename(dir_name) != dir_name:
+ raise ValueError(
+ f"Skill directory name {dir_name!r} must be a plain name "
+ f"without path separators.",
+ )
+
+ backend = self.get_backend()
+ suffix = "tar.gz" if fmt == "tar.gz" else fmt
+ archive_path = f"/tmp/skill-{_generate_id()}.{suffix}"
+
+ async with self._skill_lock:
+ await backend.exec_shell(["mkdir", "-p", self._skills_dir])
+ # Staged beside ``skills/`` rather than inside it: the same
+ # filesystem keeps the final rename atomic, while
+ # ``list_skills`` never sees a half-expanded archive.
+ staging = backend.join_path(
+ self.workdir,
+ f".skill-staging-{_generate_id()}",
+ )
+ await backend.write_stream(archive_path, stream)
+ try:
+ result = await backend.exec_shell(
+ [
+ "python3",
+ "-c",
+ _EXTRACT_ARCHIVE_SHIM,
+ archive_path,
+ staging,
+ fmt,
+ str(max_extracted_bytes),
+ ],
+ )
+ if not result.ok():
+ raise RuntimeError(
+ f"Failed to expand skill archive: "
+ f"{result.stderr.decode('utf-8', 'replace')}",
+ )
+
+ root = await self._find_skill_root(staging)
+ installed = await self._free_skill_dir(dir_name)
+ move = await backend.exec_shell(
+ [
+ "mv",
+ root,
+ backend.join_path(self._skills_dir, installed),
+ ],
+ )
+ if not move.ok():
+ raise RuntimeError(
+ f"Failed to install skill {installed!r}: "
+ f"{move.stderr.decode('utf-8', 'replace')}",
+ )
+ finally:
+ await backend.delete_path(staging)
+ await backend.delete_path(archive_path)
+
+ logger.info("Added skill %r to %s", installed, self._skills_dir)
+
+ async def _find_skill_root(self, staging: str) -> str:
+ """Return the directory under ``staging`` holding ``SKILL.md``.
+
+ Archives arrive flat or wrapped in a single top-level folder;
+ both are accepted.
+
+ Args:
+ staging (`str`):
+ The directory the archive was expanded into.
+
+ Returns:
+ `str`:
+ The path of the directory containing ``SKILL.md``.
+
+ Raises:
+ ValueError:
+ If no ``SKILL.md`` is found.
+ """
+ backend = self.get_backend()
+ if await backend.file_exists(backend.join_path(staging, "SKILL.md")):
+ return staging
+
+ for entry in await backend.list_dir(staging):
+ candidate = backend.join_path(staging, entry)
+ if await backend.file_exists(
+ backend.join_path(candidate, "SKILL.md"),
+ ):
+ return candidate
+
+ raise ValueError("The skill archive contains no SKILL.md")
+
+ async def _free_skill_dir(self, dir_name: str) -> str:
+ """Return ``dir_name``, suffixed until it is unused.
+
+ Args:
+ dir_name (`str`):
+ The preferred directory name.
+
+ Returns:
+ `str`:
+ A directory name not present in ``skills/``.
+ """
+ backend = self.get_backend()
+ candidate, counter = dir_name, 1
+ while await backend.file_exists(
+ backend.join_path(self._skills_dir, candidate),
+ ):
+ candidate = f"{dir_name}-{counter}"
+ counter += 1
+ return candidate
+
async def remove_skill(self, name: str) -> None:
"""Remove a skill by its agent-facing ``name`` (front matter).
diff --git a/src/agentscope/workspace/_bubblewrap/_bubblewrap_backend.py b/src/agentscope/workspace/_bubblewrap/_bubblewrap_backend.py
index 27bfe878c..2e80cdc2a 100644
--- a/src/agentscope/workspace/_bubblewrap/_bubblewrap_backend.py
+++ b/src/agentscope/workspace/_bubblewrap/_bubblewrap_backend.py
@@ -14,7 +14,7 @@ import os
import posixpath
import signal
from pathlib import PurePosixPath
-from typing import Any
+from typing import Any, AsyncIterator
from ...tool import BackendBase, ExecResult
from ._constants import SANDBOX_CACHE_DIR, SANDBOX_TMPDIR, SANDBOX_WORKDIR
@@ -282,6 +282,22 @@ class BubblewrapBackend(BackendBase):
async def write_file(self, path: str, data: bytes) -> None:
"""Write raw bytes, refusing every symbolic-link final component."""
+ await self._write_via_cat(path, data)
+
+ async def write_stream(
+ self,
+ path: str,
+ stream: AsyncIterator[bytes],
+ ) -> None:
+ """Stream bytes into ``path``, chunk by chunk through ``cat``."""
+ await self._write_via_cat(path, stream)
+
+ async def _write_via_cat(
+ self,
+ path: str,
+ data: bytes | AsyncIterator[bytes],
+ ) -> None:
+ """Pipe ``data`` into ``path`` via ``cat``, refusing symlinks."""
sandbox_path = self._sandbox_path_for(path)
result = await self._exec_with_input(
[
@@ -310,7 +326,7 @@ class BubblewrapBackend(BackendBase):
)
if not result.ok():
raise RuntimeError(
- "Bubblewrap write_file failed "
+ "Bubblewrap write failed "
f"(exit {result.exit_code}): "
f"{result.stderr.decode(errors='replace')}",
)
@@ -318,12 +334,18 @@ class BubblewrapBackend(BackendBase):
async def _exec_with_input(
self,
command: list[str],
- data: bytes,
+ data: bytes | AsyncIterator[bytes],
*,
cwd: str | None = None,
timeout: float | None = None,
) -> ExecResult:
- """Run a sandbox command with ``data`` piped to stdin."""
+ """Run a sandbox command with ``data`` piped to stdin.
+
+ An async iterator is fed chunk by chunk, so a large payload
+ never materializes. Safe only because the commands run this way
+ write nothing to stdout — otherwise a full pipe would deadlock
+ against the writer.
+ """
try:
process = await self.start_process(
command,
@@ -340,10 +362,11 @@ class BubblewrapBackend(BackendBase):
)
try:
- stdout, stderr = await asyncio.wait_for(
- process.communicate(data),
- timeout=timeout,
- )
+ if isinstance(data, bytes):
+ comm = process.communicate(data)
+ else:
+ comm = self._feed_then_communicate(process, data)
+ stdout, stderr = await asyncio.wait_for(comm, timeout=timeout)
except asyncio.TimeoutError:
await self._terminate_process_tree(process, grace=1.0)
return ExecResult(exit_code=-1, stdout=b"", stderr=b"timed out")
@@ -359,6 +382,19 @@ class BubblewrapBackend(BackendBase):
stderr=stderr,
)
+ @staticmethod
+ async def _feed_then_communicate(
+ process: asyncio.subprocess.Process,
+ stream: AsyncIterator[bytes],
+ ) -> tuple[bytes, bytes]:
+ """Write ``stream`` to stdin, then drain the process."""
+ assert process.stdin is not None
+ async for chunk in stream:
+ process.stdin.write(chunk)
+ await process.stdin.drain()
+ process.stdin.close()
+ return await process.communicate()
+
def _bwrap_argv(
self,
command: list[str],
diff --git a/src/agentscope/workspace/_k8s/_k8s_backend.py b/src/agentscope/workspace/_k8s/_k8s_backend.py
index aba775522..aa3826e3b 100644
--- a/src/agentscope/workspace/_k8s/_k8s_backend.py
+++ b/src/agentscope/workspace/_k8s/_k8s_backend.py
@@ -21,7 +21,7 @@ import io
import posixpath
import shlex
import tarfile
-from typing import Any
+from typing import Any, AsyncIterator
from ...tool import BackendBase, ExecResult
@@ -290,8 +290,57 @@ class K8sBackend(BackendBase):
info = tarfile.TarInfo(name=name)
info.size = len(data)
tf.addfile(info, io.BytesIO(data))
- tar_bytes = buf.getvalue()
+ await self._exec_ws_stdin(
+ ["tar", "xf", "-", "-C", parent],
+ [buf.getvalue()],
+ path,
+ )
+
+ async def write_stream(
+ self,
+ path: str,
+ stream: AsyncIterator[bytes],
+ ) -> None:
+ """Stream bytes into ``path`` inside the Pod.
+
+ Pipes to ``cat`` rather than ``tar`` because a tar header
+ needs the member size up front, which a stream cannot give.
+
+ Args:
+ path (`str`):
+ Destination path inside the Pod.
+ stream (`AsyncIterator[bytes]`):
+ The chunks to write, in order.
+ """
+ parent = posixpath.dirname(path) or "/"
+ await self.exec_shell(["mkdir", "-p", parent])
+ await self._exec_ws_stdin(
+ ["sh", "-c", 'cat > "$1"', "sh", path],
+ stream,
+ path,
+ )
+
+ async def _exec_ws_stdin(
+ self,
+ command: list[str],
+ stdin: AsyncIterator[bytes] | list[bytes],
+ path: str,
+ ) -> None:
+ """Run ``command`` in the Pod, feeding ``payload`` to stdin.
+
+ Args:
+ command (`list[str]`):
+ The argv to exec inside the container.
+ stdin (`AsyncIterator[bytes] | list[bytes]`):
+ Chunks written to stdin, in order.
+ path (`str`):
+ The destination path, for the error message only.
+
+ Raises:
+ `RuntimeError`:
+ If the command exits non-zero inside the Pod.
+ """
from kubernetes_asyncio import client as k8s_client
from kubernetes_asyncio.stream import WsApiClient
@@ -302,7 +351,7 @@ class K8sBackend(BackendBase):
ws = await v1_ws.connect_get_namespaced_pod_exec(
self._pod_name,
self._namespace,
- command=["tar", "xf", "-", "-C", parent],
+ command=command,
container=self._container_name,
stderr=True,
stdin=True,
@@ -314,9 +363,12 @@ class K8sBackend(BackendBase):
exit_code = 0
async with ws as sock:
- await sock.send_bytes(
- bytes([0]) + tar_bytes,
- )
+ if isinstance(stdin, list):
+ for chunk in stdin:
+ await sock.send_bytes(bytes([0]) + chunk)
+ else:
+ async for chunk in stdin:
+ await sock.send_bytes(bytes([0]) + chunk)
await sock.send_bytes(bytes([0]))
async for msg in sock:
@@ -353,6 +405,6 @@ class K8sBackend(BackendBase):
errors="replace",
)
raise RuntimeError(
- f"write_file to {path!r} failed: "
- f"tar xf exited {exit_code}: {stderr_text}",
+ f"write to {path!r} failed: "
+ f"{command[0]} exited {exit_code}: {stderr_text}",
)
diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.py
index 92e0fdaee..f98d7e9f5 100644
--- a/src/agentscope/workspace/_local_workspace.py
+++ b/src/agentscope/workspace/_local_workspace.py
@@ -7,18 +7,22 @@ import json
import os
import re
import shutil
-from typing import TypedDict
+from typing import AsyncIterator, Literal, TypedDict
import frontmatter
from ._utils import DEFAULT_WORKSPACE_INSTRUCTIONS
from .._logging import logger
-from .._utils._common import _normalize_local_path
+from .._utils._common import _generate_id, _normalize_local_path
from ..mcp import MCPClient
from ..skill import Skill
from ..tool import ToolBase
from ..tool._builtin._backend import LocalBackend
-from ._base import WorkspaceBase
+from ._base import (
+ DEFAULT_MAX_EXTRACTED_BYTES,
+ _EXTRACT_ARCHIVE_SHIM,
+ WorkspaceBase,
+)
class _SkillEntry(TypedDict):
@@ -686,8 +690,18 @@ class LocalWorkspace(WorkspaceBase):
Args:
mcp_client (`MCPClient`):
The MCP client to add.
+
+ Raises:
+ ValueError:
+ If an MCP with the same name already exists. Names are
+ unique because they compose the model-facing tool name
+ ``mcp__{name}__{tool}``.
"""
async with self._mcp_lock:
+ if any(m.name == mcp_client.name for m in self._mcps):
+ raise ValueError(
+ f"MCP {mcp_client.name!r} already exists in workspace.",
+ )
if mcp_client.is_stateful and not mcp_client.is_connected:
await mcp_client.connect()
self._mcps.append(mcp_client)
@@ -805,6 +819,65 @@ class LocalWorkspace(WorkspaceBase):
)
await self._save_skills_file(skills_dir, skills_file)
+ async def add_skill_archive(
+ self,
+ stream: AsyncIterator[bytes],
+ fmt: Literal["zip", "tar", "tar.gz"],
+ dir_name: str,
+ max_extracted_bytes: int = DEFAULT_MAX_EXTRACTED_BYTES,
+ ) -> None:
+ """Expand a skill archive, then install it as a local directory.
+
+ Unpacks inside the workspace and hands the result to
+ :meth:`add_skill`, so hash dedup, name conflict resolution and
+ the ``.skills`` index behave exactly as for a path install —
+ which is also why ``dir_name`` is ignored here: the directory
+ name comes from the ``SKILL.md`` front matter.
+
+ Args:
+ stream (`AsyncIterator[bytes]`):
+ The archive bytes, in order.
+ fmt (`Literal["zip", "tar", "tar.gz"]`):
+ The archive format.
+ dir_name (`str`):
+ Unused; kept for interface compatibility.
+ max_extracted_bytes (`int`):
+ Ceiling on the archive's expanded size.
+
+ Raises:
+ ValueError:
+ If the archive holds no valid ``SKILL.md``.
+ RuntimeError:
+ If expanding the archive fails.
+ """
+ staging = os.path.join(
+ self.workdir,
+ f".skill-staging-{_generate_id()}",
+ )
+ archive_path = f"{staging}.{'tar.gz' if fmt == 'tar.gz' else fmt}"
+ try:
+ await self._backend.write_stream(archive_path, stream)
+ result = await self._backend.exec_shell(
+ [
+ "python3",
+ "-c",
+ _EXTRACT_ARCHIVE_SHIM,
+ archive_path,
+ staging,
+ fmt,
+ str(max_extracted_bytes),
+ ],
+ )
+ if not result.ok():
+ raise RuntimeError(
+ f"Failed to expand skill archive: "
+ f"{result.stderr.decode('utf-8', 'replace')}",
+ )
+ await self.add_skill(await self._find_skill_root(staging))
+ finally:
+ await self._backend.delete_path(staging)
+ await self._backend.delete_path(archive_path)
+
async def remove_skill(self, name: str) -> None:
"""Remove a skill from the workspace by its agent-facing name.
diff --git a/src/agentscope/workspace/_utils.py b/src/agentscope/workspace/_utils.py
index 0686feb4a..b72cde355 100644
--- a/src/agentscope/workspace/_utils.py
+++ b/src/agentscope/workspace/_utils.py
@@ -97,10 +97,17 @@ DEFAULT_GLOB_HELPER_SCRIPT = "_glob_helper.py"
#: Minimum Python packages the gateway script needs at runtime.
#: Both Docker (image build) and E2B (sandbox bootstrap) install this
#: same tuple into the gateway venv before adding ``agentscope`` itself.
+#:
+#: ``agentscope`` goes in with ``--no-deps``, so anything it imports has
+#: to be named here — depending on another package to drag it along is
+#: what broke when ``mcp`` 2.0 swapped ``httpx`` for ``httpx2``. The
+#: bound on ``mcp`` mirrors ``pyproject.toml``, so the gateway speaks
+#: the same protocol version as the process driving it.
_GATEWAY_BASE_REQUIREMENTS: tuple[str, ...] = (
- "mcp",
+ "mcp<2.0.0",
"uvicorn",
"fastapi",
+ "httpx",
)
diff --git a/tests/docker/k8s_workspace_test.Dockerfile b/tests/docker/k8s_workspace_test.Dockerfile
index 8b51f213f..2d283a775 100644
--- a/tests/docker/k8s_workspace_test.Dockerfile
+++ b/tests/docker/k8s_workspace_test.Dockerfile
@@ -41,7 +41,7 @@ ENV GATEWAY_HOME=/root/.agentscope
RUN mkdir -p "${GATEWAY_HOME}" \
&& uv venv "${GATEWAY_HOME}/.venv" \
&& uv pip install --python "${GATEWAY_HOME}/.venv/bin/python" \
- mcp uvicorn fastapi
+ 'mcp<2.0.0' uvicorn fastapi httpx
# Install agentscope itself from the local checkout.
# Build context is repo root, so pyproject.toml + src/ are visible at /src.
diff --git a/tests/hub_card_test.py b/tests/hub_card_test.py
new file mode 100644
index 000000000..2e7bfdc16
--- /dev/null
+++ b/tests/hub_card_test.py
@@ -0,0 +1,97 @@
+# -*- coding: utf-8 -*-
+"""Hub card identity test case."""
+from unittest import TestCase
+
+from agentscope.app.hub import HubBase, MCPCard, SkillCard
+
+HTTP_CONFIG = {"type": "http_mcp", "url": "https://example.com/sse"}
+
+
+class HubIdentityTest(TestCase):
+ """Hub id validation."""
+
+ def test_accepts_plain_id(self) -> None:
+ """A ``[a-zA-Z0-9_-]+`` id is accepted."""
+ hub = HubBase("claw_hub-1", "ClawHub")
+
+ self.assertEqual(hub.hub_id, "claw_hub-1")
+ self.assertEqual(hub.description, "")
+
+ def test_rejects_colon(self) -> None:
+ """A colon is not usable in a route path segment."""
+ with self.assertRaises(ValueError):
+ HubBase("claw:hub", "ClawHub")
+
+ def test_rejects_empty(self) -> None:
+ """An empty id is rejected."""
+ with self.assertRaises(ValueError):
+ HubBase("", "ClawHub")
+
+
+class CardIdentityTest(TestCase):
+ """Card id defaulting and cross-hub disambiguation."""
+
+ def test_mcp_id_defaults_to_name(self) -> None:
+ """A hub exposing no separate id falls back to the name."""
+ card = MCPCard(
+ hub_id="testhub",
+ name="notion",
+ config_template=HTTP_CONFIG,
+ )
+
+ self.assertEqual(card.id, "notion")
+
+ def test_mcp_id_kept_when_given(self) -> None:
+ """An explicit id is preserved independently of the name."""
+ card = MCPCard(
+ hub_id="testhub",
+ id="srv_01ab",
+ name="notion",
+ config_template=HTTP_CONFIG,
+ )
+
+ self.assertEqual(card.id, "srv_01ab")
+ self.assertEqual(card.name, "notion")
+
+ def test_skill_id_defaults_to_name(self) -> None:
+ """The skill card follows the same defaulting rule."""
+ card = SkillCard(hub_id="clawhub", name="gifgrep")
+
+ self.assertEqual(card.id, "gifgrep")
+
+ def test_opaque_id_with_colon(self) -> None:
+ """A card id may contain a colon — ClawHub's search ids do.
+
+ This is why the global handle stays the ``(hub_id, id)`` pair
+ rather than a joined string, which could not be split back.
+ """
+ card = SkillCard(
+ hub_id="clawhub",
+ id="clawhub:kd75911hf60t9b6fr5pn61x0fx80t3xw",
+ name="git",
+ )
+
+ self.assertEqual(
+ card.id,
+ "clawhub:kd75911hf60t9b6fr5pn61x0fx80t3xw",
+ )
+
+ def test_same_name_across_hubs_differs(self) -> None:
+ """The pair is what disambiguates a shared name."""
+ a = SkillCard(hub_id="clawhub", name="git")
+ b = SkillCard(hub_id="otherhub", name="git")
+
+ self.assertEqual(a.name, b.name)
+ self.assertNotEqual((a.hub_id, a.id), (b.hub_id, b.id))
+
+ def test_rename_keeps_provenance(self) -> None:
+ """Renaming a card touches ``name`` only; the source survives."""
+ card = MCPCard(
+ hub_id="clawhub",
+ name="git",
+ config_template=HTTP_CONFIG,
+ )
+
+ card.name = "git-2"
+
+ self.assertEqual((card.hub_id, card.id), ("clawhub", "git"))
diff --git a/tests/hub_claw_test.py b/tests/hub_claw_test.py
new file mode 100644
index 000000000..9b2603a8d
--- /dev/null
+++ b/tests/hub_claw_test.py
@@ -0,0 +1,110 @@
+# -*- coding: utf-8 -*-
+"""ClawHub card-building test case, without any network."""
+from unittest import TestCase
+
+from agentscope.app.hub import ClawSkillHub
+
+
+class ClawCardTest(TestCase):
+ """Turning an upstream catalog record into a ``SkillCard``."""
+
+ def setUp(self) -> None:
+ """Build a hub with no token; nothing here makes a request."""
+ self.hub = ClawSkillHub()
+
+ def _card(self, **item: object) -> object:
+ """Build a card from a catalog record with sane defaults."""
+ # pylint: disable=protected-access
+ return self.hub._to_card({"slug": "demo", **item})
+
+ def test_timestamp_version_renders_as_a_date(self) -> None:
+ """ClawHub's generator stamps ``0.<date>.<time>`` versions."""
+ card = self._card(latestVersion={"version": "0.20260729.110214"})
+
+ self.assertEqual(card.version, "2026-07-29")
+
+ def test_semver_is_left_alone(self) -> None:
+ """A hub that versions properly is never rewritten."""
+ card = self._card(latestVersion={"version": "1.0.1"})
+
+ self.assertEqual(card.version, "1.0.1")
+
+ def test_timestamp_shaped_but_invalid_date_is_left_alone(self) -> None:
+ """Eight digits that are not a date stay verbatim."""
+ card = self._card(latestVersion={"version": "0.20261399.110214"})
+
+ self.assertEqual(card.version, "0.20261399.110214")
+
+ def test_missing_version_stays_none(self) -> None:
+ """The search endpoint reports no version at all."""
+ self.assertIsNone(self._card().version)
+
+ def test_topics_become_tags(self) -> None:
+ """Upstream ``tags`` is a version map, so ``topics`` is used."""
+ card = self._card(
+ topics=["development"],
+ tags={"latest": "0.20260729.110214"},
+ )
+
+ self.assertEqual(card.tags, ["development"])
+
+ def test_updated_at_converted_from_millis(self) -> None:
+ """``updatedAt`` is reported in Unix milliseconds."""
+ card = self._card(updatedAt=1785300394493)
+
+ self.assertAlmostEqual(card.updated_at, 1785300394.493, places=3)
+
+ def test_installs_come_from_stats(self) -> None:
+ """``stats.installs`` is the count worth showing."""
+ card = self._card(stats={"installs": 25, "downloads": 888})
+
+ self.assertEqual(card.installs, 25)
+
+ def test_installs_stay_none_without_stats(self) -> None:
+ """No stats means unknown, which is not the same as zero."""
+ self.assertIsNone(self._card().installs)
+
+ def test_url_falls_back_to_the_slug_route(self) -> None:
+ """The catalog endpoint carries no link, so one is built."""
+ card = self._card()
+
+ self.assertEqual(card.url, "https://clawhub.ai/skills/demo")
+
+ def test_canonical_url_is_preferred(self) -> None:
+ """The search endpoint knows the owner-scoped path."""
+ card = self._card(canonicalUrl="/someone/skills/demo")
+
+ self.assertEqual(card.url, "https://clawhub.ai/someone/skills/demo")
+
+ def test_author_and_icon_from_the_detail_owner(self) -> None:
+ """The detail endpoint puts the owner beside the skill."""
+ card = self._card(
+ owner={"displayName": "Len", "handle": "lentiancn", "image": "u"},
+ )
+
+ self.assertEqual(card.author, "Len")
+ self.assertEqual(card.icon_url, "u")
+
+ def test_author_falls_back_to_the_handle(self) -> None:
+ """Not every owner sets a display name."""
+ card = self._card(owner={"handle": "lentiancn"})
+
+ self.assertEqual(card.author, "lentiancn")
+
+ def test_owner_read_from_the_search_shape(self) -> None:
+ """Search nests the owner under ``native``."""
+ card = self._card(native={"owner": {"handle": "someone"}})
+
+ self.assertEqual(card.author, "someone")
+
+ def test_catalog_records_have_no_author(self) -> None:
+ """The catalog endpoint omits the owner entirely."""
+ card = self._card(stats={"downloads": 496})
+
+ self.assertIsNone(card.author)
+ self.assertIsNone(card.icon_url)
+
+ def test_downloads_from_either_shape(self) -> None:
+ """Nested under ``stats`` on the catalog, top level on search."""
+ self.assertEqual(self._card(stats={"downloads": 496}).downloads, 496)
+ self.assertEqual(self._card(downloads=17058).downloads, 17058)
diff --git a/tests/hub_github_test.py b/tests/hub_github_test.py
new file mode 100644
index 000000000..5962baca0
--- /dev/null
+++ b/tests/hub_github_test.py
@@ -0,0 +1,158 @@
+# -*- coding: utf-8 -*-
+"""GitHub MCP registry card-building test case, without any network."""
+from unittest import TestCase
+
+from agentscope.app._service import render_mcp
+from agentscope.app.hub import GitHubMCPHub
+
+
+class GitHubCardTest(TestCase):
+ """Turning a registry entry into an ``MCPCard``."""
+
+ def setUp(self) -> None:
+ """Build a hub; nothing here makes a request."""
+ self.hub = GitHubMCPHub()
+
+ def _card(self, server: dict, github: dict | None = None) -> object:
+ """Build a card from a registry entry with sane defaults."""
+ # pylint: disable=protected-access
+ return self.hub._to_card(
+ {
+ "server": {"id": "abc", "name": "acme/thing", **server},
+ "x-github": github or {},
+ },
+ )
+
+ def test_remote_becomes_an_http_config(self) -> None:
+ """A ``remotes`` entry is reachable over HTTP, so not stateful."""
+ card = self._card(
+ {"remotes": [{"transport_type": "streamable-http", "url": "u"}]},
+ )
+
+ self.assertEqual(card.config_template.type, "http_mcp")
+ self.assertFalse(card.is_stateful)
+ self.assertEqual(card.auth, "none")
+
+ def test_secret_header_becomes_an_input(self) -> None:
+ """A ``{VAR}`` placeholder is declared so the user must fill it."""
+ card = self._card(
+ {
+ "remotes": [
+ {
+ "url": "u",
+ "headers": [
+ {
+ "value": "Bearer {TOKEN}",
+ "is_secret": True,
+ "description": "The token.",
+ },
+ ],
+ },
+ ],
+ },
+ )
+
+ self.assertEqual(card.auth, "inputs")
+ prop = card.inputs_schema["properties"]["TOKEN"]
+ self.assertTrue(prop["writeOnly"])
+ self.assertEqual(prop["format"], "password")
+ # Rewritten to the ``${...}`` form the renderer understands.
+ headers = card.config_template.headers
+ self.assertEqual(headers["Authorization"], "Bearer ${TOKEN}")
+ client = render_mcp(card, {"TOKEN": "sk"})
+ self.assertEqual(
+ client.mcp_config.headers["Authorization"],
+ "Bearer sk",
+ )
+
+ def test_package_becomes_a_stdio_config(self) -> None:
+ """A runnable package is a local process, so stateful."""
+ card = self._card(
+ {
+ "packages": [
+ {"name": "pkg", "version": "1.2.3", "runtime_hint": "npx"},
+ ],
+ },
+ )
+
+ self.assertEqual(card.config_template.type, "stdio_mcp")
+ self.assertEqual(card.config_template.command, "npx")
+ self.assertEqual(card.config_template.args, ["-y", "[email protected]"])
+ self.assertTrue(card.is_stateful)
+
+ def test_secret_env_var_becomes_an_input(self) -> None:
+ """Package secrets are declared the same way header ones are."""
+ card = self._card(
+ {
+ "packages": [
+ {
+ "name": "pkg",
+ "runtime_hint": "uvx",
+ "environment_variables": [
+ {"name": "API_KEY", "is_secret": True},
+ ],
+ },
+ ],
+ },
+ )
+
+ self.assertIn("API_KEY", card.inputs_schema["properties"])
+ self.assertEqual(card.config_template.env["API_KEY"], "${API_KEY}")
+
+ def test_unrunnable_package_is_skipped(self) -> None:
+ """Around a third of the catalog names a package without saying
+ how to run it; listing it would offer an install that cannot
+ work."""
+ self.assertIsNone(self._card({"packages": [{"name": "pkg"}]}))
+ self.assertIsNone(self._card({}))
+
+ def test_remote_wins_over_package(self) -> None:
+ """Reaching a hosted endpoint beats spawning a local process."""
+ card = self._card(
+ {
+ "remotes": [{"url": "u"}],
+ "packages": [{"name": "p", "runtime_hint": "npx"}],
+ },
+ )
+
+ self.assertEqual(card.config_template.type, "http_mcp")
+
+ def test_name_is_slugged_for_the_mcp_client(self) -> None:
+ """Registry names carry ``/`` and ``.``; client names may not."""
+ card = self._card(
+ {"name": "io.github.upstash/context7", "remotes": [{"url": "u"}]},
+ )
+
+ self.assertEqual(card.name, "context7")
+ self.assertEqual(card.id, "abc")
+
+ def test_display_fields_come_from_the_github_block(self) -> None:
+ """Author, icon and language ride along on ``x-github``."""
+ card = self._card(
+ {
+ "remotes": [{"url": "u"}],
+ "updated_at": "2026-01-21T09:35:10Z",
+ "repository": {"url": "https://github.com/acme/thing"},
+ "version_detail": {"version": "1.0.0"},
+ },
+ {
+ "name_with_owner": "acme/thing",
+ "preferred_image": "https://avatars/acme",
+ "primary_language": "Python",
+ "display_name": "Thing",
+ },
+ )
+
+ self.assertEqual(card.author, "acme")
+ self.assertEqual(card.icon_url, "https://avatars/acme")
+ self.assertEqual(card.tags, ["Python"])
+ self.assertEqual(card.display_name, "Thing")
+ self.assertEqual(card.url, "https://github.com/acme/thing")
+ self.assertEqual(card.version, "1.0.0")
+ self.assertIsNotNone(card.updated_at)
+
+ def test_bad_timestamp_is_dropped_not_fatal(self) -> None:
+ """A malformed date must not sink the whole card."""
+ card = self._card({"remotes": [{"url": "u"}], "updated_at": "soon"})
+
+ self.assertIsNone(card.updated_at)
diff --git a/tests/hub_router_test.py b/tests/hub_router_test.py
new file mode 100644
index 000000000..2d1fe5e29
--- /dev/null
+++ b/tests/hub_router_test.py
@@ -0,0 +1,787 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=too-many-public-methods
+"""Hub router test case — browse and install, without any network."""
+import io
+import json
+import tempfile
+import zipfile
+from typing import Any, AsyncIterator
+from unittest import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+from fastapi.testclient import TestClient
+
+from agentscope.app import create_app
+from agentscope.app.hub import (
+ MCPCard,
+ MCPHubBase,
+ MCPHubPage,
+ SkillCard,
+ SkillHubBase,
+ SkillHubPage,
+)
+from agentscope.app.message_bus import RedisMessageBus
+from agentscope.app.storage import RedisStorage
+from agentscope.app.workspace_manager import LocalWorkspaceManager
+
+HEADERS = {"X-User-ID": "alice"}
+
+SKILL_MD = """---
+name: gifgrep
+description: Find GIFs.
+---
+
+# gifgrep
+"""
+
+
+def _zip_bytes(files: dict) -> bytes:
+ """Build an in-memory ZIP from ``{name: text}``."""
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ for name, text in files.items():
+ archive.writestr(name, text)
+ return buffer.getvalue()
+
+
+class FakeMCPHub(MCPHubBase):
+ """A three-card MCP hub: one public, one behind an API key, and one
+ carrying the display metadata an install snapshots."""
+
+ def __init__(self) -> None:
+ """Register the fixture cards."""
+ super().__init__("fake", "Fake MCP Hub", "For testing.")
+ self.cards = {
+ "tagged": MCPCard(
+ hub_id="fake",
+ name="tagged",
+ display_name="Tagged",
+ description="A card with metadata.",
+ tags=["search", "docs"],
+ auth="none",
+ config_template={
+ "type": "http_mcp",
+ "url": "https://tagged.invalid/sse",
+ },
+ ),
+ "echo": MCPCard(
+ hub_id="fake",
+ name="echo",
+ auth="none",
+ is_stateful=False,
+ config_template={
+ "type": "http_mcp",
+ "url": "https://echo.invalid/sse",
+ },
+ ),
+ "notion": MCPCard(
+ hub_id="fake",
+ name="notion",
+ inputs_schema={
+ "type": "object",
+ "properties": {
+ "api_key": {
+ "type": "string",
+ "writeOnly": True,
+ "format": "password",
+ },
+ },
+ "required": ["api_key"],
+ },
+ config_template={
+ "type": "http_mcp",
+ "url": "https://notion.invalid/sse",
+ "headers": {"Authorization": "Bearer ${api_key}"},
+ },
+ ),
+ }
+
+ async def list_mcps(
+ self,
+ user_id: str,
+ q: str | None = None,
+ cursor: str | None = None,
+ limit: int = 20,
+ ) -> MCPHubPage:
+ """Return the fixture cards, filtered by ``q``."""
+ cards = [
+ card for card in self.cards.values() if not q or q in card.name
+ ]
+ return MCPHubPage(cards=cards[:limit])
+
+ async def get_mcp(self, user_id: str, card_id: str) -> MCPCard:
+ """Return one fixture card."""
+ return self.cards[card_id]
+
+
+class FakeSkillHub(SkillHubBase):
+ """A one-card skill hub serving an in-memory archive."""
+
+ def __init__(self) -> None:
+ """Register the fixture card."""
+ super().__init__("fakeskills", "Fake Skill Hub")
+ self.card = SkillCard(
+ hub_id="fakeskills",
+ name="gifgrep",
+ display_name="GIF Grep",
+ description="Find GIFs.",
+ tags=["media"],
+ author="Len",
+ icon_url="https://avatars.invalid/len",
+ url="https://hub.invalid/skills/gifgrep",
+ markdown=SKILL_MD,
+ )
+ self.download_users: list[str] = []
+
+ async def list_skills(
+ self,
+ user_id: str,
+ q: str | None = None,
+ cursor: str | None = None,
+ limit: int = 20,
+ ) -> SkillHubPage:
+ """Return the single fixture card."""
+ return SkillHubPage(cards=[self.card], next_cursor="page-2")
+
+ async def get_skill(self, user_id: str, card_id: str) -> SkillCard:
+ """Return the fixture card, or raise for anything else."""
+ if card_id != "gifgrep":
+ raise KeyError(card_id)
+ return self.card
+
+ async def download(
+ self,
+ user_id: str,
+ card_id: str,
+ version: str | None = None,
+ ) -> AsyncIterator[bytes]:
+ """Yield an in-memory ZIP, or raise for an unknown card."""
+ self.download_users.append(user_id)
+ if card_id == "nozip":
+ yield b"not a zip at all"
+ return
+ if card_id == "nomd":
+ yield _zip_bytes({"README.md": "nothing here"})
+ return
+ if card_id != "gifgrep":
+ raise KeyError(card_id)
+ yield _zip_bytes({"SKILL.md": SKILL_MD, "notes.md": "x"})
+
+
+def _fake_backends() -> tuple:
+ """Build a fakeredis-backed storage and message bus."""
+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
+
+ class _Storage(RedisStorage):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ class _Bus(RedisMessageBus):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ return _Storage(), _Bus()
+
+
+class HubRouterTest(IsolatedAsyncioTestCase):
+ """Browse and install through the hub endpoints."""
+
+ def setUp(self) -> None:
+ """Start an app wired to the fake hubs and a local workspace."""
+ # enterContext is the unittest-native way to bind a context
+ # manager to the test's lifetime; pylint does not recognise it.
+ # pylint: disable=consider-using-with
+ workdir = self.enterContext(tempfile.TemporaryDirectory())
+ storage, bus = _fake_backends()
+ self._skill_hub = FakeSkillHub()
+ app = create_app(
+ storage=storage,
+ message_bus=bus,
+ workspace_manager=LocalWorkspaceManager(workdir),
+ mcp_hubs=[FakeMCPHub()],
+ skill_hubs=[self._skill_hub],
+ enable_index_worker=False,
+ )
+ self._client = self.enterContext(TestClient(app))
+
+ agent_id = self._client.post(
+ "/agent/",
+ json={"name": "tester", "system_prompt": "hi"},
+ headers=HEADERS,
+ ).json()["agent_id"]
+ session_id = self._client.post(
+ "/sessions/",
+ json={"agent_id": agent_id},
+ headers=HEADERS,
+ ).json()["session_id"]
+ self._scope = {"agent_id": agent_id, "session_id": session_id}
+
+ # ── browse ────────────────────────────────────────────────────
+
+ def test_lists_hubs(self) -> None:
+ """Each kind lists only its own hubs."""
+ mcp = self._client.get("/hub/mcp", headers=HEADERS).json()
+ skill = self._client.get("/hub/skill", headers=HEADERS).json()
+
+ self.assertEqual([h["hub_id"] for h in mcp], ["fake"])
+ self.assertEqual([h["hub_id"] for h in skill], ["fakeskills"])
+ self.assertEqual(mcp[0]["display_name"], "Fake MCP Hub")
+
+ def test_browses_cards(self) -> None:
+ """Cards come back with the inputs the user must fill."""
+ body = self._client.get(
+ "/hub/mcp/fake/cards",
+ headers=HEADERS,
+ ).json()
+
+ names = [c["name"] for c in body["cards"]]
+ self.assertEqual(sorted(names), ["echo", "notion", "tagged"])
+ notion = next(c for c in body["cards"] if c["name"] == "notion")
+ prop = notion["inputs_schema"]["properties"]["api_key"]
+ self.assertTrue(prop["writeOnly"])
+
+ def test_search_and_cursor_are_forwarded(self) -> None:
+ """``q`` filters, and the hub's cursor reaches the caller."""
+ filtered = self._client.get(
+ "/hub/mcp/fake/cards",
+ params={"q": "not"},
+ headers=HEADERS,
+ ).json()
+ skills = self._client.get(
+ "/hub/skill/fakeskills/cards",
+ headers=HEADERS,
+ ).json()
+
+ self.assertEqual([c["name"] for c in filtered["cards"]], ["notion"])
+ self.assertEqual(skills["next_cursor"], "page-2")
+
+ def test_unknown_hub(self) -> None:
+ """An unregistered hub id is a 404."""
+ response = self._client.get("/hub/mcp/nope/cards", headers=HEADERS)
+
+ self.assertEqual(response.status_code, 404)
+
+ def test_unknown_card(self) -> None:
+ """An unknown card id is a 404."""
+ response = self._client.get(
+ "/hub/skill/fakeskills/cards/missing",
+ headers=HEADERS,
+ )
+
+ self.assertEqual(response.status_code, 404)
+
+ # ── install: MCP ──────────────────────────────────────────────
+
+ def _install_mcp(self, card_id: str, **body: Any) -> Any:
+ """POST an MCP install. Installing is user-level, so unlike the
+ skill endpoint it takes no session scope."""
+ return self._client.post(
+ f"/hub/mcp/fake/cards/{card_id}/install",
+ json=body,
+ headers=HEADERS,
+ )
+
+ def test_install_rejects_missing_value(self) -> None:
+ """A required input the caller omitted is a 400."""
+ response = self._install_mcp("notion", values={})
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("api_key", response.json()["detail"])
+
+ def test_install_rejects_wrong_type(self) -> None:
+ """A value violating the schema type is a 400."""
+ response = self._install_mcp("notion", values={"api_key": 123})
+
+ self.assertEqual(response.status_code, 400)
+
+ def test_install_lands_in_the_library(self) -> None:
+ """A successful install shows up under ``GET /mcp`` carrying the
+ provenance of the card it came from."""
+ response = self._install_mcp("notion", values={"api_key": "sk"})
+
+ self.assertEqual(response.status_code, 201)
+ self.assertEqual(response.json()["name"], "notion")
+
+ listed = self._client.get("/mcp", headers=HEADERS).json()
+ self.assertEqual(len(listed), 1)
+ self.assertEqual(listed[0]["hub_id"], "fake")
+ self.assertEqual(listed[0]["card_id"], "notion")
+ self.assertTrue(listed[0]["enabled"])
+
+ def test_install_snapshots_the_display_fields(self) -> None:
+ """Description and tags are copied, so the library can still show
+ them when the hub is gone."""
+ self._install_mcp("tagged")
+
+ listed = self._client.get("/mcp", headers=HEADERS).json()
+ self.assertEqual(listed[0]["display_name"], "Tagged")
+ self.assertEqual(listed[0]["description"], "A card with metadata.")
+ self.assertEqual(listed[0]["tags"], ["search", "docs"])
+
+ def test_install_does_not_touch_the_workspace(self) -> None:
+ """Installing is user-level — no session's workspace changes."""
+ self._install_mcp("echo")
+
+ listed = self._client.get(
+ "/workspace/mcp",
+ params=self._scope,
+ headers=HEADERS,
+ ).json()
+ self.assertEqual([m["name"] for m in listed], [])
+
+ def test_install_never_echoes_the_rendered_config(self) -> None:
+ """The response must not hand the submitted secret back."""
+ body = self._install_mcp(
+ "notion",
+ values={"api_key": "sk"},
+ ).json()
+
+ self.assertNotIn("mcp_config", body)
+ self.assertNotIn("sk", json.dumps(body))
+
+ def test_install_rejects_duplicate_name(self) -> None:
+ """The MCP name is unique per user."""
+ self._install_mcp("echo")
+ response = self._install_mcp("echo")
+
+ self.assertEqual(response.status_code, 409)
+ self.assertEqual(
+ len(self._client.get("/mcp", headers=HEADERS).json()),
+ 1,
+ )
+
+ def test_install_under_a_custom_name(self) -> None:
+ """A caller can sidestep a clash by naming the install."""
+ self._install_mcp("echo")
+ response = self._install_mcp("echo", name="echo-2")
+
+ self.assertEqual(response.status_code, 201)
+ names = [
+ m["name"] for m in self._client.get("/mcp", headers=HEADERS).json()
+ ]
+ self.assertEqual(names, ["echo", "echo-2"])
+
+ def test_uninstall_removes_it_from_the_library(self) -> None:
+ """Deleting frees the record and its name."""
+ mcp_id = self._install_mcp("echo").json()["id"]
+
+ self.assertEqual(
+ self._client.delete(f"/mcp/{mcp_id}", headers=HEADERS).status_code,
+ 204,
+ )
+ self.assertEqual(self._client.get("/mcp", headers=HEADERS).json(), [])
+ self.assertEqual(
+ self._client.delete(f"/mcp/{mcp_id}", headers=HEADERS).status_code,
+ 404,
+ )
+
+ def test_library_is_per_user(self) -> None:
+ """One user's install is invisible to another."""
+ self._install_mcp("echo")
+
+ listed = self._client.get(
+ "/mcp",
+ headers={"X-User-ID": "someone-else"},
+ ).json()
+ self.assertEqual(listed, [])
+
+ async def test_rekey_rerenders_the_config(self) -> None:
+ """A new API key is a re-render: the secret can sit anywhere in
+ the config, so only the card's template knows where to put it."""
+ mcp_id = self._install_mcp(
+ "notion",
+ values={"api_key": "old"},
+ ).json()["id"]
+
+ response = self._client.patch(
+ f"/mcp/{mcp_id}",
+ json={"values": {"api_key": "new"}},
+ headers=HEADERS,
+ )
+
+ self.assertEqual(response.status_code, 200)
+ # Never echoed back — the response carries no config at all.
+ self.assertNotIn("new", json.dumps(response.json()))
+
+ # Read the record back to see the key actually moved into the
+ # header the template puts it in.
+ storage = self._client.app.state.storage
+ record = await storage.get_mcp("alice", mcp_id)
+ auth = record.client.mcp_config.headers["Authorization"]
+ self.assertEqual(auth, "Bearer new")
+ self.assertEqual(record.values, {"api_key": "new"})
+
+ async def test_rekey_merges_over_the_stored_answers(self) -> None:
+ """Only the changed key is sent, so a write-only field the form
+ never echoed back must survive untouched."""
+ mcp_id = self._install_mcp(
+ "notion",
+ values={"api_key": "old"},
+ ).json()["id"]
+
+ self._client.patch(
+ f"/mcp/{mcp_id}",
+ json={"name": "notion-2"},
+ headers=HEADERS,
+ )
+
+ storage = self._client.app.state.storage
+ record = await storage.get_mcp("alice", mcp_id)
+ self.assertEqual(record.values, {"api_key": "old"})
+ self.assertEqual(record.client.name, "notion-2")
+
+ def test_rename_keeps_the_config(self) -> None:
+ """Renaming touches the name, not the rendered config."""
+ mcp_id = self._install_mcp("echo").json()["id"]
+
+ response = self._client.patch(
+ f"/mcp/{mcp_id}",
+ json={"name": "echo-renamed"},
+ headers=HEADERS,
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["name"], "echo-renamed")
+
+ def test_rename_onto_a_taken_name_is_a_conflict(self) -> None:
+ """Names stay unique per user through edits too."""
+ self._install_mcp("echo")
+ mcp_id = self._install_mcp("tagged").json()["id"]
+
+ response = self._client.patch(
+ f"/mcp/{mcp_id}",
+ json={"name": "echo"},
+ headers=HEADERS,
+ )
+
+ self.assertEqual(response.status_code, 409)
+
+ def test_disable_keeps_the_record(self) -> None:
+ """A disabled MCP is kept so re-enabling does not lose config."""
+ mcp_id = self._install_mcp("echo").json()["id"]
+
+ response = self._client.patch(
+ f"/mcp/{mcp_id}",
+ json={"enabled": False},
+ headers=HEADERS,
+ )
+
+ self.assertFalse(response.json()["enabled"])
+ self.assertEqual(
+ len(self._client.get("/mcp", headers=HEADERS).json()),
+ 1,
+ )
+
+ def test_update_missing_returns_404(self) -> None:
+ """Editing an MCP that is not in the library is a 404."""
+ response = self._client.patch(
+ "/mcp/no-such-id",
+ json={"enabled": False},
+ headers=HEADERS,
+ )
+
+ self.assertEqual(response.status_code, 404)
+
+ # ── workspace <-> library ─────────────────────────────────────
+
+ def test_hand_added_mcp_lands_in_the_library(self) -> None:
+ """One typed in by hand is reusable next session, and carries no
+ card, which is what marks it as un-rekeyable."""
+ self._client.post(
+ "/workspace/mcp",
+ params=self._scope,
+ json={
+ "name": "hand-rolled",
+ "is_stateful": False,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://hand.invalid/sse",
+ },
+ },
+ headers=HEADERS,
+ )
+
+ listed = self._client.get("/mcp", headers=HEADERS).json()
+ self.assertEqual([m["name"] for m in listed], ["hand-rolled"])
+ self.assertIsNone(listed[0]["hub_id"])
+
+ def test_library_definition_is_not_redefined_by_a_second_add(
+ self,
+ ) -> None:
+ """The library is where an MCP is defined; adding it to another
+ workspace must not silently overwrite that."""
+ mcp_id = self._install_mcp("echo").json()["id"]
+
+ self._client.post(
+ "/workspace/mcp",
+ params=self._scope,
+ json={
+ "name": "echo",
+ "is_stateful": False,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://different.invalid/sse",
+ },
+ },
+ headers=HEADERS,
+ )
+
+ listed = self._client.get("/mcp", headers=HEADERS).json()
+ self.assertEqual(len(listed), 1)
+ # Still the record the install created, hub provenance intact.
+ self.assertEqual(listed[0]["id"], mcp_id)
+ self.assertEqual(listed[0]["hub_id"], "fake")
+
+ def test_add_from_library_reports_each_pick(self) -> None:
+ """A bad pick must not throw away the good ones."""
+ mcp_id = self._install_mcp("echo").json()["id"]
+
+ response = self._client.post(
+ "/workspace/mcp/from-library",
+ params=self._scope,
+ json={"mcp_ids": [mcp_id, "no-such-id"]},
+ headers=HEADERS,
+ )
+
+ body = response.json()
+ self.assertEqual(body["added"], ["echo"])
+ self.assertIn("no-such-id", body["failed"])
+ self.assertEqual(len(body["failed"]), 1)
+ listed = self._client.get(
+ "/workspace/mcp",
+ params=self._scope,
+ headers=HEADERS,
+ ).json()
+ self.assertEqual([m["name"] for m in listed], ["echo"])
+
+ def test_add_from_library_skips_what_is_already_there(self) -> None:
+ """Adding twice is a no-op, not a duplicate or an error."""
+ mcp_id = self._install_mcp("echo").json()["id"]
+ payload = {"mcp_ids": [mcp_id]}
+ self._client.post(
+ "/workspace/mcp/from-library",
+ params=self._scope,
+ json=payload,
+ headers=HEADERS,
+ )
+
+ again = self._client.post(
+ "/workspace/mcp/from-library",
+ params=self._scope,
+ json=payload,
+ headers=HEADERS,
+ ).json()
+
+ self.assertEqual(again["added"], [])
+ self.assertEqual(again["failed"], {})
+
+ def test_unreachable_mcp_reports_why(self) -> None:
+ """A red dot alone is not actionable — the reason has to reach
+ the client, unwrapped out of the transport's task group."""
+ self._client.post(
+ "/workspace/mcp",
+ params=self._scope,
+ json={
+ "name": "broken",
+ "is_stateful": False,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "http://127.0.0.1:1/mcp",
+ "timeout": 1.0,
+ },
+ },
+ headers=HEADERS,
+ )
+
+ listed = self._client.get(
+ "/workspace/mcp",
+ params=self._scope,
+ headers=HEADERS,
+ ).json()
+
+ self.assertFalse(listed[0]["is_healthy"])
+ detail = listed[0]["error"]
+ self.assertTrue(detail)
+ # The bare ExceptionGroup message says nothing useful; the leaf
+ # cause is what has to come through.
+ self.assertNotIn("TaskGroup", detail)
+
+ # ── install: skill ────────────────────────────────────────────
+
+ def _install_skill(self, card_id: str, **params: str) -> Any:
+ """POST a skill install. User-level, like the MCP one."""
+ return self._client.post(
+ f"/hub/skill/fakeskills/cards/{card_id}/install",
+ params=params,
+ headers=HEADERS,
+ )
+
+ def test_install_skill_lands_in_the_library(self) -> None:
+ """A successful install shows up under ``GET /skill``."""
+ response = self._install_skill("gifgrep")
+
+ self.assertEqual(response.status_code, 201)
+ self.assertEqual(response.json()["name"], "gifgrep")
+
+ listed = self._client.get("/skill", headers=HEADERS).json()
+ self.assertEqual(len(listed), 1)
+ self.assertEqual(listed[0]["hub_id"], "fakeskills")
+ self.assertEqual(listed[0]["card_id"], "gifgrep")
+
+ def test_install_snapshots_the_display_identity(self) -> None:
+ """Author, icon and link survive the install, so the library
+ does not lose the listing's identity the moment it is added."""
+ self._install_skill("gifgrep")
+
+ listed = self._client.get("/skill", headers=HEADERS).json()[0]
+ self.assertEqual(listed["author"], "Len")
+ self.assertEqual(listed["icon_url"], "https://avatars.invalid/len")
+ self.assertEqual(listed["url"], "https://hub.invalid/skills/gifgrep")
+
+ def test_install_skill_does_not_touch_the_workspace(self) -> None:
+ """Installing is user-level — no session's workspace changes."""
+ self._install_skill("gifgrep")
+
+ listed = self._client.get(
+ "/workspace/skill",
+ params=self._scope,
+ headers=HEADERS,
+ ).json()
+ self.assertEqual([s["name"] for s in listed], [])
+
+ def test_install_skill_does_not_download(self) -> None:
+ """The archive is fetched when the skill reaches a workspace,
+ not when it is added to the library."""
+ self._install_skill("gifgrep")
+
+ self.assertEqual(self._skill_hub.download_users, [])
+
+ def test_skill_detail_carries_the_markdown(self) -> None:
+ """The list view omits ``SKILL.md``; the detail view has it."""
+ skill_id = self._install_skill("gifgrep").json()["id"]
+
+ self.assertNotIn(
+ "markdown",
+ self._client.get("/skill", headers=HEADERS).json()[0],
+ )
+ detail = self._client.get(f"/skill/{skill_id}", headers=HEADERS)
+ self.assertEqual(detail.json()["markdown"], SKILL_MD)
+
+ def test_install_skill_rejects_duplicate_name(self) -> None:
+ """The skill name is unique per user."""
+ self._install_skill("gifgrep")
+ response = self._install_skill("gifgrep")
+
+ self.assertEqual(response.status_code, 409)
+ self.assertEqual(
+ len(self._client.get("/skill", headers=HEADERS).json()),
+ 1,
+ )
+
+ def test_install_skill_under_a_custom_name(self) -> None:
+ """A caller can sidestep a clash by naming the install."""
+ self._install_skill("gifgrep")
+ response = self._install_skill("gifgrep", name="gifgrep-2")
+
+ self.assertEqual(response.status_code, 201)
+ names = [
+ s["name"]
+ for s in self._client.get("/skill", headers=HEADERS).json()
+ ]
+ self.assertEqual(names, ["gifgrep", "gifgrep-2"])
+
+ def test_install_unknown_skill(self) -> None:
+ """A card the hub does not have is a 404."""
+ response = self._install_skill("missing")
+
+ self.assertEqual(response.status_code, 404)
+
+ def test_uninstall_skill(self) -> None:
+ """Deleting frees the record and its name."""
+ skill_id = self._install_skill("gifgrep").json()["id"]
+
+ self.assertEqual(
+ self._client.delete(
+ f"/skill/{skill_id}",
+ headers=HEADERS,
+ ).status_code,
+ 204,
+ )
+ self.assertEqual(
+ self._client.get("/skill", headers=HEADERS).json(),
+ [],
+ )
+ self.assertEqual(
+ self._client.delete(
+ f"/skill/{skill_id}",
+ headers=HEADERS,
+ ).status_code,
+ 404,
+ )
+
+ def test_skill_library_is_per_user(self) -> None:
+ """One user's install is invisible to another."""
+ self._install_skill("gifgrep")
+
+ listed = self._client.get(
+ "/skill",
+ headers={"X-User-ID": "someone-else"},
+ ).json()
+ self.assertEqual(listed, [])
+
+
+class HubRegistrationTest(IsolatedAsyncioTestCase):
+ """Hub registration invariants and workspace name uniqueness."""
+
+ def test_rejects_duplicate_hub_ids(self) -> None:
+ """Two hubs sharing an id could not be told apart in the routes."""
+ storage, bus = _fake_backends()
+ with tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaises(ValueError) as ctx:
+ create_app(
+ storage=storage,
+ message_bus=bus,
+ workspace_manager=LocalWorkspaceManager(tmp),
+ skill_hubs=[FakeSkillHub(), FakeSkillHub()],
+ enable_index_worker=False,
+ )
+
+ self.assertIn("fakeskills", str(ctx.exception))
+
+ async def test_local_workspace_rejects_duplicate_mcp(self) -> None:
+ """Names compose ``mcp__{name}__{tool}``, so they must be unique.
+
+ The sandboxed backends already enforced this; the local one used
+ to append silently.
+ """
+ from agentscope.mcp import MCPClient
+ from agentscope.workspace import LocalWorkspace
+
+ with tempfile.TemporaryDirectory() as tmp:
+ workspace = LocalWorkspace(workdir=tmp)
+ await workspace.initialize()
+
+ def _client() -> MCPClient:
+ return MCPClient(
+ name="git",
+ is_stateful=False,
+ mcp_config={
+ "type": "http_mcp",
+ "url": "https://example.invalid/sse",
+ },
+ )
+
+ await workspace.add_mcp(_client())
+ with self.assertRaises(ValueError) as ctx:
+ await workspace.add_mcp(_client())
+
+ self.assertIn("already exists", str(ctx.exception))
+ self.assertEqual(len(await workspace.list_mcps()), 1)
diff --git a/tests/service_mcp_render_test.py b/tests/service_mcp_render_test.py
new file mode 100644
index 000000000..4b6b4b2e2
--- /dev/null
+++ b/tests/service_mcp_render_test.py
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+"""MCP card rendering test case."""
+from unittest import TestCase
+
+from agentscope.app._service import MCPRenderError, render_mcp
+from agentscope.app.hub import MCPCard
+
+API_KEY_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "api_key": {
+ "type": "string",
+ "writeOnly": True,
+ "format": "password",
+ },
+ },
+ "required": ["api_key"],
+}
+
+
+def _http_card(**config: object) -> MCPCard:
+ """Build an HTTP card around the given config overrides."""
+ return MCPCard(
+ hub_id="testhub",
+ name="notion",
+ inputs_schema=API_KEY_SCHEMA,
+ config_template={
+ "type": "http_mcp",
+ "url": "https://mcp.example.com/sse",
+ **config,
+ },
+ )
+
+
+class MCPRenderTest(TestCase):
+ """The MCP card rendering test case."""
+
+ def test_substitutes_url_and_headers(self) -> None:
+ """Placeholders are filled in both the URL and header values."""
+ card = _http_card(
+ url="https://mcp.example.com/sse?key=${api_key}",
+ headers={"Authorization": "Bearer ${api_key}"},
+ )
+
+ client = render_mcp(card, {"api_key": "sk-secret"})
+
+ self.assertEqual(
+ client.mcp_config.url,
+ "https://mcp.example.com/sse?key=sk-secret",
+ )
+ self.assertEqual(
+ client.mcp_config.headers,
+ {"Authorization": "Bearer sk-secret"},
+ )
+ self.assertEqual(client.name, "notion")
+
+ def test_substitutes_stdio_args_and_env(self) -> None:
+ """Placeholders are filled inside list items and env values."""
+ card = MCPCard(
+ hub_id="testhub",
+ name="local",
+ inputs_schema=API_KEY_SCHEMA,
+ config_template={
+ "type": "stdio_mcp",
+ "command": "uvx",
+ "args": ["server", "--token", "${api_key}"],
+ "env": {"API_KEY": "${api_key}"},
+ },
+ )
+
+ client = render_mcp(card, {"api_key": "sk-secret"})
+
+ self.assertEqual(
+ client.mcp_config.args,
+ ["server", "--token", "sk-secret"],
+ )
+ self.assertEqual(client.mcp_config.env, {"API_KEY": "sk-secret"})
+
+ def test_literal_braces_survive(self) -> None:
+ """A literal ``{}`` in the config is not treated as a placeholder.
+
+ This is the regression that motivated ``string.Template`` over
+ ``str.format``.
+ """
+ card = _http_card(
+ url="https://mcp.example.com/{tenant}/sse",
+ headers={
+ "X-Filter": '{"kind": "all"}',
+ "Authorization": "Bearer ${api_key}",
+ },
+ )
+
+ client = render_mcp(card, {"api_key": "sk-secret"})
+
+ self.assertEqual(
+ client.mcp_config.url,
+ "https://mcp.example.com/{tenant}/sse",
+ )
+ self.assertEqual(
+ client.mcp_config.headers["X-Filter"],
+ '{"kind": "all"}',
+ )
+ self.assertEqual(
+ client.mcp_config.headers["Authorization"],
+ "Bearer sk-secret",
+ )
+
+ def test_undeclared_dollar_survives(self) -> None:
+ """A ``$VAR`` the card does not declare is left untouched."""
+ card = MCPCard(
+ hub_id="testhub",
+ name="local",
+ inputs_schema=API_KEY_SCHEMA,
+ config_template={
+ "type": "stdio_mcp",
+ "command": "uvx",
+ "args": ["--config", "$HOME/.config", "${api_key}"],
+ },
+ )
+
+ client = render_mcp(card, {"api_key": "sk-secret"})
+
+ self.assertEqual(
+ client.mcp_config.args,
+ ["--config", "$HOME/.config", "sk-secret"],
+ )
+
+ def test_missing_required_value(self) -> None:
+ """A missing required input is rejected by the schema."""
+ card = _http_card(headers={"Authorization": "Bearer ${api_key}"})
+
+ with self.assertRaises(MCPRenderError) as ctx:
+ render_mcp(card, {})
+
+ self.assertIn("api_key", str(ctx.exception))
+
+ def test_wrong_value_type(self) -> None:
+ """A value violating the schema type is rejected."""
+ card = _http_card(headers={"Authorization": "Bearer ${api_key}"})
+
+ with self.assertRaises(MCPRenderError):
+ render_mcp(card, {"api_key": 12345})
+
+ def test_missing_optional_value_is_reported(self) -> None:
+ """An optional input still referenced by the template errors.
+
+ ``safe_substitute`` would silently leave ``${region}`` in the
+ URL, so the unfilled placeholder is reported instead.
+ """
+ card = MCPCard(
+ hub_id="testhub",
+ name="notion",
+ inputs_schema={
+ "type": "object",
+ "properties": {"region": {"type": "string"}},
+ },
+ config_template={
+ "type": "http_mcp",
+ "url": "https://${region}.example.com/sse",
+ },
+ )
+
+ with self.assertRaises(MCPRenderError) as ctx:
+ render_mcp(card, {})
+
+ self.assertIn("region", str(ctx.exception))
+
+ def test_no_inputs_card(self) -> None:
+ """A card with no inputs renders as-is."""
+ card = MCPCard(
+ hub_id="testhub",
+ name="public",
+ auth="none",
+ config_template={
+ "type": "http_mcp",
+ "url": "https://public.example.com/sse",
+ },
+ )
+
+ client = render_mcp(card, {})
+
+ self.assertEqual(
+ client.mcp_config.url,
+ "https://public.example.com/sse",
+ )
+
+ def test_name_override(self) -> None:
+ """The caller can rename the installed client."""
+ card = _http_card()
+
+ client = render_mcp(card, {"api_key": "sk"}, name="my-notion")
+
+ self.assertEqual(client.name, "my-notion")
+
+ def test_invalid_client_name(self) -> None:
+ """A slug the MCP client rejects surfaces as a render error."""
+ card = MCPCard(
+ hub_id="testhub",
+ name="not.a.valid.name",
+ config_template={
+ "type": "http_mcp",
+ "url": "https://public.example.com/sse",
+ },
+ )
+
+ with self.assertRaises(MCPRenderError) as ctx:
+ render_mcp(card, {})
+
+ self.assertIn("invalid client", str(ctx.exception))
diff --git a/tests/storage_redis_test.py b/tests/storage_redis_test.py
index f4fec20b5..d0f558acb 100644
--- a/tests/storage_redis_test.py
+++ b/tests/storage_redis_test.py
@@ -18,7 +18,9 @@ from agentscope.app.storage import (
TeamData,
TeamRecord,
)
+from agentscope.app.storage import MCPRecord, SkillRecord
from agentscope.credential import OllamaCredential
+from agentscope.mcp import HttpMCPConfig, MCPClient
from agentscope.app.storage import AgentData
from agentscope.agent import ContextConfig, ReActConfig
from agentscope.message import UserMsg, AssistantMsg, TextBlock
@@ -1211,3 +1213,308 @@ class TestTeamCascade(IsolatedAsyncioTestCase):
"""delete_team on a missing team returns False without crashing."""
result = await self.storage.delete_team(self.user_id, "no-such-id")
self.assertFalse(result)
+
+
+def make_mcp_record(
+ user_id: str,
+ name: str = "deepwiki",
+ **kwargs: object,
+) -> MCPRecord:
+ """Create a test MCPRecord wrapping a stateless HTTP MCP."""
+ return MCPRecord(
+ user_id=user_id,
+ client=MCPClient(
+ name=name,
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(url="https://mcp.deepwiki.com/mcp"),
+ ),
+ **kwargs,
+ )
+
+
+class TestMCP(IsolatedAsyncioTestCase):
+ """Tests for installed-MCP CRUD and the per-user name uniqueness."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up test fixtures."""
+ self.storage = make_storage()
+ self.user_id = "user-mcp"
+
+ async def test_upsert_and_get_roundtrip(self) -> None:
+ """A written record comes back with its provenance intact."""
+ record = make_mcp_record(
+ self.user_id,
+ hub_id="static",
+ card_id="deepwiki",
+ version="1.0.0",
+ )
+ mcp_id = await self.storage.upsert_mcp(self.user_id, record)
+
+ fetched = await self.storage.get_mcp(self.user_id, mcp_id)
+ self.assertIsNotNone(fetched)
+ self.assertEqual(fetched.client.name, "deepwiki")
+ self.assertEqual(fetched.client.mcp_config.type, "http_mcp")
+ self.assertEqual(fetched.hub_id, "static")
+ self.assertEqual(fetched.card_id, "deepwiki")
+ self.assertEqual(fetched.version, "1.0.0")
+ self.assertTrue(fetched.enabled)
+
+ async def test_manually_added_mcp_has_no_provenance(self) -> None:
+ """An MCP added by hand still gets a record, just without a hub."""
+ record = make_mcp_record(self.user_id, name="hand-rolled")
+ await self.storage.upsert_mcp(self.user_id, record)
+
+ fetched = await self.storage.get_mcp_by_name(
+ self.user_id,
+ "hand-rolled",
+ )
+ self.assertIsNotNone(fetched)
+ self.assertIsNone(fetched.hub_id)
+ self.assertIsNone(fetched.card_id)
+
+ async def test_duplicate_name_rejected(self) -> None:
+ """Two records may not share a name — the workspace joins on it."""
+ await self.storage.upsert_mcp(
+ self.user_id,
+ make_mcp_record(self.user_id),
+ )
+ with self.assertRaises(ValueError):
+ await self.storage.upsert_mcp(
+ self.user_id,
+ make_mcp_record(self.user_id),
+ )
+
+ async def test_same_name_across_users_allowed(self) -> None:
+ """Uniqueness is per user, not global."""
+ await self.storage.upsert_mcp(
+ self.user_id,
+ make_mcp_record(self.user_id),
+ )
+ other = await self.storage.upsert_mcp(
+ "other-user",
+ make_mcp_record("other-user"),
+ )
+ self.assertIsNotNone(await self.storage.get_mcp("other-user", other))
+
+ async def test_update_in_place_keeps_name_claim(self) -> None:
+ """Re-upserting the same record is an update, not a name clash."""
+ record = make_mcp_record(self.user_id)
+ mcp_id = await self.storage.upsert_mcp(self.user_id, record)
+
+ record.enabled = False
+ await self.storage.upsert_mcp(self.user_id, record)
+
+ fetched = await self.storage.get_mcp(self.user_id, mcp_id)
+ self.assertFalse(fetched.enabled)
+ self.assertEqual(len(await self.storage.list_mcps(self.user_id)), 1)
+
+ async def test_rename_releases_the_old_name(self) -> None:
+ """After a rename the old name is free and no longer resolves."""
+ record = make_mcp_record(self.user_id)
+ await self.storage.upsert_mcp(self.user_id, record)
+
+ record.client.name = "deepwiki-2"
+ await self.storage.upsert_mcp(self.user_id, record)
+
+ self.assertIsNone(
+ await self.storage.get_mcp_by_name(self.user_id, "deepwiki"),
+ )
+ self.assertIsNotNone(
+ await self.storage.get_mcp_by_name(self.user_id, "deepwiki-2"),
+ )
+ # The freed name can now be claimed by a different record
+ await self.storage.upsert_mcp(
+ self.user_id,
+ make_mcp_record(self.user_id),
+ )
+ self.assertEqual(len(await self.storage.list_mcps(self.user_id)), 2)
+
+ async def test_delete_frees_the_name(self) -> None:
+ """Deleting a record releases its name for reuse."""
+ record = make_mcp_record(self.user_id)
+ mcp_id = await self.storage.upsert_mcp(self.user_id, record)
+
+ self.assertTrue(await self.storage.delete_mcp(self.user_id, mcp_id))
+ self.assertIsNone(
+ await self.storage.get_mcp_by_name(self.user_id, "deepwiki"),
+ )
+ self.assertEqual(await self.storage.list_mcps(self.user_id), [])
+
+ await self.storage.upsert_mcp(
+ self.user_id,
+ make_mcp_record(self.user_id),
+ )
+
+ async def test_delete_missing_returns_false(self) -> None:
+ """delete_mcp on a missing record returns False without crashing."""
+ self.assertFalse(
+ await self.storage.delete_mcp(self.user_id, "no-such-id"),
+ )
+
+ async def test_get_by_unknown_name_returns_none(self) -> None:
+ """An unclaimed name resolves to nothing."""
+ self.assertIsNone(
+ await self.storage.get_mcp_by_name(self.user_id, "nope"),
+ )
+
+
+def make_skill_record(
+ user_id: str,
+ name: str = "gifgrep",
+ **kwargs: object,
+) -> SkillRecord:
+ """Create a test SkillRecord."""
+ return SkillRecord(user_id=user_id, name=name, **kwargs)
+
+
+class TestSkill(IsolatedAsyncioTestCase):
+ """Tests for installed-skill CRUD and per-user name uniqueness."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up test fixtures."""
+ self.storage = make_storage()
+ self.user_id = "user-skill"
+
+ async def test_upsert_and_get_roundtrip(self) -> None:
+ """A written record comes back with its provenance intact."""
+ record = make_skill_record(
+ self.user_id,
+ hub_id="clawhub",
+ card_id="gifgrep",
+ version="1.0.1",
+ markdown="# gifgrep",
+ )
+ skill_id = await self.storage.upsert_skill(self.user_id, record)
+
+ fetched = await self.storage.get_skill(
+ self.user_id,
+ skill_id,
+ )
+ self.assertIsNotNone(fetched)
+ self.assertEqual(fetched.name, "gifgrep")
+ self.assertEqual(fetched.hub_id, "clawhub")
+ self.assertEqual(fetched.markdown, "# gifgrep")
+ self.assertTrue(fetched.enabled)
+
+ async def test_duplicate_name_rejected(self) -> None:
+ """Two records may not share a name."""
+ await self.storage.upsert_skill(
+ self.user_id,
+ make_skill_record(self.user_id),
+ )
+ with self.assertRaises(ValueError):
+ await self.storage.upsert_skill(
+ self.user_id,
+ make_skill_record(self.user_id),
+ )
+
+ async def test_same_name_across_users_allowed(self) -> None:
+ """Uniqueness is per user, not global."""
+ await self.storage.upsert_skill(
+ self.user_id,
+ make_skill_record(self.user_id),
+ )
+ other = await self.storage.upsert_skill(
+ "other-user",
+ make_skill_record("other-user"),
+ )
+ self.assertIsNotNone(
+ await self.storage.get_skill("other-user", other),
+ )
+
+ async def test_update_in_place_keeps_name_claim(self) -> None:
+ """Re-upserting the same record is an update, not a name clash."""
+ record = make_skill_record(self.user_id)
+ skill_id = await self.storage.upsert_skill(self.user_id, record)
+
+ record.enabled = False
+ await self.storage.upsert_skill(self.user_id, record)
+
+ fetched = await self.storage.get_skill(
+ self.user_id,
+ skill_id,
+ )
+ self.assertFalse(fetched.enabled)
+ self.assertEqual(
+ len(await self.storage.list_skills(self.user_id)),
+ 1,
+ )
+
+ async def test_rename_releases_the_old_name(self) -> None:
+ """After a rename the old name is free and no longer resolves."""
+ record = make_skill_record(self.user_id)
+ await self.storage.upsert_skill(self.user_id, record)
+
+ record.name = "gifgrep-2"
+ await self.storage.upsert_skill(self.user_id, record)
+
+ self.assertIsNone(
+ await self.storage.get_skill_by_name(
+ self.user_id,
+ "gifgrep",
+ ),
+ )
+ self.assertIsNotNone(
+ await self.storage.get_skill_by_name(
+ self.user_id,
+ "gifgrep-2",
+ ),
+ )
+ await self.storage.upsert_skill(
+ self.user_id,
+ make_skill_record(self.user_id),
+ )
+ self.assertEqual(
+ len(await self.storage.list_skills(self.user_id)),
+ 2,
+ )
+
+ async def test_delete_frees_the_name(self) -> None:
+ """Deleting a record releases its name for reuse."""
+ record = make_skill_record(self.user_id)
+ skill_id = await self.storage.upsert_skill(self.user_id, record)
+
+ self.assertTrue(
+ await self.storage.delete_skill(self.user_id, skill_id),
+ )
+ self.assertIsNone(
+ await self.storage.get_skill_by_name(
+ self.user_id,
+ "gifgrep",
+ ),
+ )
+ self.assertEqual(
+ await self.storage.list_skills(self.user_id),
+ [],
+ )
+
+ await self.storage.upsert_skill(
+ self.user_id,
+ make_skill_record(self.user_id),
+ )
+
+ async def test_delete_missing_returns_false(self) -> None:
+ """Deleting a missing record returns False without crashing."""
+ self.assertFalse(
+ await self.storage.delete_skill(
+ self.user_id,
+ "no-such-id",
+ ),
+ )
+
+ async def test_mcp_and_skill_libraries_are_independent(self) -> None:
+ """The two name indexes do not collide."""
+ await self.storage.upsert_mcp(
+ self.user_id,
+ make_mcp_record(self.user_id, name="shared"),
+ )
+ await self.storage.upsert_skill(
+ self.user_id,
+ make_skill_record(self.user_id, name="shared"),
+ )
+
+ self.assertEqual(len(await self.storage.list_mcps(self.user_id)), 1)
+ self.assertEqual(
+ len(await self.storage.list_skills(self.user_id)),
+ 1,
+ )
diff --git a/tests/storage_sql_test.py b/tests/storage_sql_test.py
index b44998169..2e20c95f4 100644
--- a/tests/storage_sql_test.py
+++ b/tests/storage_sql_test.py
@@ -24,10 +24,12 @@ from agentscope.app.storage import (
KnowledgeBaseRecord,
KnowledgeDocumentData,
KnowledgeDocumentRecord,
+ MCPRecord,
ScheduleData,
ScheduleRecord,
SessionConfig,
SessionSource,
+ SkillRecord,
AsyncSQLAlchemyStorage,
TeamData,
TeamMember,
@@ -35,6 +37,7 @@ from agentscope.app.storage import (
)
from agentscope.agent import ContextConfig, ReActConfig
from agentscope.credential import DashScopeCredential
+from agentscope.mcp import HttpMCPConfig, MCPClient
from agentscope.message import AssistantMsg, UserMsg
@@ -117,6 +120,18 @@ def _schedule_record(user_id: str, agent_id: str) -> ScheduleRecord:
)
+def _mcp_record(user_id: str, name: str = "deepwiki") -> MCPRecord:
+ """Build an installed-MCP record wrapping a stateless HTTP MCP."""
+ return MCPRecord(
+ user_id=user_id,
+ client=MCPClient(
+ name=name,
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(url="https://mcp.deepwiki.com/mcp"),
+ ),
+ )
+
+
class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):
"""End-to-end tests for :class:`AsyncSQLAlchemyStorage` over
in-memory SQLite."""
@@ -778,6 +793,100 @@ class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):
await self.storage.delete_schedule("user-1", s1.id),
)
+ # ------------------------------------------------------------------
+ # Installed MCPs and skills
+ # ------------------------------------------------------------------
+
+ async def test_mcps_round_trip(self) -> None:
+ """Upsert / get / get-by-name / list / delete + owner scoping."""
+ record = _mcp_record("user-1")
+ mcp_id = await self.storage.upsert_mcp("user-1", record)
+
+ fetched = await self.storage.get_mcp("user-1", mcp_id)
+ self.assertEqual(fetched.client.mcp_config.type, "http_mcp")
+ self.assertEqual(fetched.name, "deepwiki")
+
+ by_name = await self.storage.get_mcp_by_name("user-1", "deepwiki")
+ self.assertEqual(by_name.id, mcp_id)
+ self.assertIsNone(
+ await self.storage.get_mcp_by_name("user-1", "nope"),
+ )
+
+ self.assertEqual(
+ [m.id for m in await self.storage.list_mcps("user-1")],
+ [mcp_id],
+ )
+ self.assertEqual(await self.storage.list_mcps("user-2"), [])
+ self.assertIsNone(await self.storage.get_mcp("user-2", mcp_id))
+
+ self.assertTrue(await self.storage.delete_mcp("user-1", mcp_id))
+ self.assertFalse(await self.storage.delete_mcp("user-1", mcp_id))
+
+ async def test_mcp_name_is_unique_per_user(self) -> None:
+ """A second record may not claim a name, but another user may."""
+ await self.storage.upsert_mcp("user-1", _mcp_record("user-1"))
+ with self.assertRaises(ValueError):
+ await self.storage.upsert_mcp("user-1", _mcp_record("user-1"))
+
+ other = await self.storage.upsert_mcp("user-2", _mcp_record("user-2"))
+ self.assertIsNotNone(await self.storage.get_mcp("user-2", other))
+
+ async def test_mcp_rename_frees_the_old_name(self) -> None:
+ """Re-upserting the same record renames rather than clashing."""
+ record = _mcp_record("user-1")
+ await self.storage.upsert_mcp("user-1", record)
+
+ record.client.name = "renamed"
+ await self.storage.upsert_mcp("user-1", record)
+
+ self.assertIsNone(
+ await self.storage.get_mcp_by_name("user-1", "deepwiki"),
+ )
+ renamed = await self.storage.get_mcp_by_name("user-1", "renamed")
+ self.assertEqual(renamed.id, record.id)
+
+ async def test_skills_round_trip(self) -> None:
+ """Upsert / get / get-by-name / list / delete + owner scoping."""
+ record = SkillRecord(user_id="user-1", name="gifgrep")
+ skill_id = await self.storage.upsert_skill("user-1", record)
+
+ fetched = await self.storage.get_skill("user-1", skill_id)
+ self.assertEqual(fetched.name, "gifgrep")
+
+ by_name = await self.storage.get_skill_by_name("user-1", "gifgrep")
+ self.assertEqual(by_name.id, skill_id)
+
+ self.assertEqual(
+ [s.id for s in await self.storage.list_skills("user-1")],
+ [skill_id],
+ )
+ self.assertEqual(await self.storage.list_skills("user-2"), [])
+ self.assertIsNone(await self.storage.get_skill("user-2", skill_id))
+
+ self.assertTrue(await self.storage.delete_skill("user-1", skill_id))
+ self.assertFalse(await self.storage.delete_skill("user-1", skill_id))
+
+ async def test_skill_name_is_unique_per_user(self) -> None:
+ """Mirrors the MCP rule; the two libraries are independent."""
+ await self.storage.upsert_skill(
+ "user-1",
+ SkillRecord(user_id="user-1", name="shared"),
+ )
+ with self.assertRaises(ValueError):
+ await self.storage.upsert_skill(
+ "user-1",
+ SkillRecord(user_id="user-1", name="shared"),
+ )
+
+ # The same name on the MCP side is a different table entirely.
+ await self.storage.upsert_mcp(
+ "user-1",
+ _mcp_record("user-1", name="shared"),
+ )
+ self.assertIsNotNone(
+ await self.storage.get_mcp_by_name("user-1", "shared"),
+ )
+
class AsyncSQLAlchemyStorageAutoMigrateTest(IsolatedAsyncioTestCase):
"""Boot via ``auto_migrate=True`` and confirm the schema is live.
@@ -854,3 +963,26 @@ class LegacyRecordShapeTest(IsolatedAsyncioTestCase):
self.assertEqual(record.status, "ready")
# The fields moved to the top level and no longer shadow ``data``.
self.assertNotIn("status", record.data.model_dump())
+
+ async def test_mcp_name_is_derived_not_read(self) -> None:
+ """``MCPRecord.name`` comes from the client, so a payload written
+ before the field existed — or one carrying a stale value — still
+ yields the right name."""
+ for stored_name in (None, "stale"):
+ payload: dict = {
+ "user_id": "u1",
+ "client": {
+ "name": "deepwiki",
+ "is_stateful": False,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://mcp.deepwiki.com/mcp",
+ },
+ },
+ }
+ if stored_name is not None:
+ payload["name"] = stored_name
+ self.assertEqual(
+ MCPRecord.model_validate(payload).name,
+ "deepwiki",
+ )
diff --git a/tests/toolkit_test.py b/tests/toolkit_test.py
index 0d3d96846..e9a1ea222 100644
--- a/tests/toolkit_test.py
+++ b/tests/toolkit_test.py
@@ -10,6 +10,7 @@ from unittest.async_case import IsolatedAsyncioTestCase
from utils import AnyString
+from agentscope.mcp import HttpMCPConfig, MCPClient
from agentscope.state import AgentState
from agentscope.message import (
TextBlock,
@@ -1365,6 +1366,28 @@ The tool instructions are a collection of suggestions, rules and notifications a
},
)
+ async def test_broken_mcp_is_skipped_not_fatal(self) -> None:
+ """One unreachable MCP must not take the whole reply down with
+ it: an expired token or a server that is simply down would
+ otherwise end the conversation instead of just withdrawing that
+ server's tools."""
+ toolkit = Toolkit(
+ mcps=[
+ MCPClient(
+ name="broken",
+ is_stateful=False,
+ # Nothing listens on port 1; the connection is
+ # refused rather than hanging.
+ mcp_config=HttpMCPConfig(
+ url="http://127.0.0.1:1/mcp",
+ timeout=1.0,
+ ),
+ ),
+ ],
+ )
+
+ self.assertEqual(await toolkit.get_tool_schemas(), [])
+
class RemoveTitleFieldTest(TestCase):
"""Unit tests for _remove_title_field."""
diff --git a/tests/workspace_bubblewrap_test.py b/tests/workspace_bubblewrap_test.py
index a7e27b30b..e7cdc7cee 100644
--- a/tests/workspace_bubblewrap_test.py
+++ b/tests/workspace_bubblewrap_test.py
@@ -1015,7 +1015,10 @@ class TestBubblewrapWorkspace(IsolatedAsyncioTestCase):
is_stateful=True,
mcp_config=StdioMCPConfig(
command="uvx",
- args=["mcp-server-time"],
+ # Constrained because the client is pinned to mcp<2:
+ # unpinned, uvx now resolves an mcp 2.x server, whose
+ # handshake this client cannot complete.
+ args=["--with", "mcp<2.0.0", "mcp-server-time"],
),
)
await self.workspace.add_mcp(mcp_client)
diff --git a/tests/workspace_k8s_test.py b/tests/workspace_k8s_test.py
index 8dac2ca64..eb9299f5b 100644
--- a/tests/workspace_k8s_test.py
+++ b/tests/workspace_k8s_test.py
@@ -195,7 +195,10 @@ class TestK8sWorkspaceHappyPath(IsolatedAsyncioTestCase):
is_stateful=True,
mcp_config=StdioMCPConfig(
command="uvx",
- args=["mcp-server-time"],
+ # Constrained because the client is pinned to mcp<2:
+ # unpinned, uvx now resolves an mcp 2.x server, whose
+ # handshake this client cannot complete.
+ args=["--with", "mcp<2.0.0", "mcp-server-time"],
),
)
self.assertListEqual(await ws.list_mcps(), [])
diff --git a/tests/workspace_skill_archive_test.py b/tests/workspace_skill_archive_test.py
new file mode 100644
index 000000000..3febb5ace
--- /dev/null
+++ b/tests/workspace_skill_archive_test.py
@@ -0,0 +1,287 @@
+# -*- coding: utf-8 -*-
+"""Test cases for installing a skill from an archive stream."""
+import io
+import os
+import tarfile
+import tempfile
+import zipfile
+from typing import AsyncIterator
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from fastapi import UploadFile
+
+from agentscope.app._service._skill_upload import (
+ SkillUploadError,
+ UploadManifest,
+ _tar_stream,
+ _validate_manifest,
+)
+from agentscope.workspace import LocalWorkspace
+from agentscope.workspace._base import WorkspaceBase
+
+
+async def _chunks(data: bytes, size: int = 11) -> AsyncIterator[bytes]:
+ """Yield ``data`` in small pieces, so streaming is actually tested."""
+ for i in range(0, len(data), size):
+ yield data[i : i + size]
+
+
+def _zip(files: dict[str, str]) -> bytes:
+ """Build a ZIP archive from a path -> content mapping."""
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as archive:
+ for path, content in files.items():
+ archive.writestr(path, content)
+ return buf.getvalue()
+
+
+def _tar(files: dict[str, str]) -> bytes:
+ """Build a tar archive from a path -> content mapping."""
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w") as archive:
+ for path, content in files.items():
+ data = content.encode("utf-8")
+ info = tarfile.TarInfo(name=path)
+ info.size = len(data)
+ archive.addfile(info, io.BytesIO(data))
+ return buf.getvalue()
+
+
+def _skill_md(name: str) -> str:
+ """Return a minimal valid ``SKILL.md``."""
+ return f"---\nname: {name}\ndescription: a test skill\n---\nbody"
+
+
+class AddSkillArchiveLocalTest(IsolatedAsyncioTestCase):
+ """The LocalWorkspace override, which reuses the path installer."""
+
+ async def asyncSetUp(self) -> None:
+ """Open a workspace in a temporary directory."""
+ # enterContext is the unittest equivalent of "with", which
+ # pylint does not recognize.
+ # pylint: disable=consider-using-with
+ self.tmp = self.enterContext(tempfile.TemporaryDirectory())
+ self.workspace = LocalWorkspace(workdir=self.tmp)
+ await self.workspace.initialize()
+
+ async def test_install_zip_and_tar(self) -> None:
+ """Both formats land, named from the front matter."""
+ await self.workspace.add_skill_archive(
+ _chunks(_zip({"pack/SKILL.md": _skill_md("alpha")})),
+ "zip",
+ "pack",
+ )
+ await self.workspace.add_skill_archive(
+ _chunks(_tar({"pack/SKILL.md": _skill_md("beta")})),
+ "tar",
+ "pack",
+ )
+ names = sorted(s.name for s in await self.workspace.list_skills())
+ self.assertEqual(names, ["alpha", "beta"])
+
+ async def test_duplicate_is_skipped(self) -> None:
+ """The same skill twice is deduped by SKILL.md hash."""
+ payload = _zip({"pack/SKILL.md": _skill_md("alpha")})
+ await self.workspace.add_skill_archive(
+ _chunks(payload),
+ "zip",
+ "pack",
+ )
+ await self.workspace.add_skill_archive(
+ _chunks(payload),
+ "zip",
+ "pack",
+ )
+ self.assertEqual(len(await self.workspace.list_skills()), 1)
+
+ async def test_traversing_archive_is_refused(self) -> None:
+ """A member escaping the staging directory fails the install."""
+ with self.assertRaises(RuntimeError):
+ await self.workspace.add_skill_archive(
+ _chunks(_zip({"../evil.txt": "pwn"})),
+ "zip",
+ "pack",
+ )
+ self.assertFalse(
+ os.path.exists(os.path.join(self.tmp, "..", "evil.txt")),
+ )
+
+ async def test_archive_without_skill_md_is_refused(self) -> None:
+ """An archive with no SKILL.md anywhere is rejected."""
+ with self.assertRaises(ValueError):
+ await self.workspace.add_skill_archive(
+ _chunks(_zip({"pack/readme.md": "hi"})),
+ "zip",
+ "pack",
+ )
+
+ async def test_nothing_is_left_behind(self) -> None:
+ """Staging directories and archives do not survive an install."""
+ await self.workspace.add_skill_archive(
+ _chunks(_zip({"pack/SKILL.md": _skill_md("alpha")})),
+ "zip",
+ "pack",
+ )
+ self.assertEqual(
+ sorted(os.listdir(self.tmp)),
+ [".mcp", "skills"],
+ )
+
+
+class AddSkillArchiveSandboxedTest(IsolatedAsyncioTestCase):
+ """The base implementation, exercised over a local backend.
+
+ Calling the unbound base method covers the code every sandboxed
+ workspace runs, without needing a container.
+ """
+
+ async def asyncSetUp(self) -> None:
+ """Open a workspace in a temporary directory."""
+ # enterContext is the unittest equivalent of "with", which
+ # pylint does not recognize.
+ # pylint: disable=consider-using-with
+ self.tmp = self.enterContext(tempfile.TemporaryDirectory())
+ self.workspace = LocalWorkspace(workdir=self.tmp)
+ await self.workspace.initialize()
+ self.skills_dir = os.path.join(self.tmp, "skills")
+
+ async def test_directory_name_is_suffixed_when_taken(self) -> None:
+ """A repeated name gets a numeric suffix rather than an error."""
+ for index in range(3):
+ await WorkspaceBase.add_skill_archive(
+ self.workspace,
+ _chunks(_zip({"pack/SKILL.md": _skill_md(f"s{index}")})),
+ "zip",
+ "pack",
+ )
+ self.assertEqual(
+ sorted(os.listdir(self.skills_dir)),
+ ["pack", "pack-1", "pack-2"],
+ )
+
+ async def test_flat_archive_is_accepted(self) -> None:
+ """SKILL.md at the archive root needs no wrapping folder."""
+ await WorkspaceBase.add_skill_archive(
+ self.workspace,
+ _chunks(_zip({"SKILL.md": _skill_md("flat")})),
+ "zip",
+ "flat-pack",
+ )
+ self.assertEqual(os.listdir(self.skills_dir), ["flat-pack"])
+
+ async def test_oversized_expansion_is_refused(self) -> None:
+ """An archive expanding past the cap fails inside the sandbox."""
+ payload = _zip({"pack/SKILL.md": _skill_md("big") + "A" * 5000})
+ with self.assertRaises(RuntimeError) as ctx:
+ await WorkspaceBase.add_skill_archive(
+ self.workspace,
+ _chunks(payload),
+ "zip",
+ "pack",
+ max_extracted_bytes=100,
+ )
+ self.assertIn("expands to", str(ctx.exception))
+ self.assertEqual(os.listdir(self.skills_dir), [])
+
+ async def test_rejects_a_path_as_directory_name(self) -> None:
+ """A dir_name with separators never reaches the filesystem."""
+ with self.assertRaises(ValueError):
+ await WorkspaceBase.add_skill_archive(
+ self.workspace,
+ _chunks(_zip({"pack/SKILL.md": _skill_md("x")})),
+ "zip",
+ "../escape",
+ )
+
+
+class UploadManifestTest(IsolatedAsyncioTestCase):
+ """Manifest validation and the tar stream built from it."""
+
+ @staticmethod
+ def _manifest(files: dict[str, bytes]) -> UploadManifest:
+ """Describe ``files`` the way the browser would."""
+ return UploadManifest.model_validate(
+ {
+ "entries": [
+ {"path": path, "size": len(data)}
+ for path, data in files.items()
+ ],
+ },
+ )
+
+ @staticmethod
+ def _uploads(files: dict[str, bytes]) -> list[UploadFile]:
+ """Wrap ``files`` as multipart parts."""
+ return [
+ UploadFile(file=io.BytesIO(data), filename=path)
+ for path, data in files.items()
+ ]
+
+ def test_root_is_returned(self) -> None:
+ """A well-formed manifest yields its single root folder."""
+ manifest = self._manifest(
+ {"pack/SKILL.md": b"x", "pack/lib/run.py": b"y"},
+ )
+ self.assertEqual(_validate_manifest(manifest), "pack")
+
+ def test_rejects_multiple_roots(self) -> None:
+ """Files from two folders are not one skill."""
+ manifest = self._manifest({"a/SKILL.md": b"x", "b/run.py": b"y"})
+ with self.assertRaises(SkillUploadError):
+ _validate_manifest(manifest)
+
+ def test_rejects_traversal(self) -> None:
+ """A ``..`` segment is refused before anything is read."""
+ manifest = self._manifest({"pack/../../SKILL.md": b"x"})
+ with self.assertRaises(SkillUploadError):
+ _validate_manifest(manifest)
+
+ def test_rejects_missing_skill_md(self) -> None:
+ """The root must hold a SKILL.md."""
+ manifest = self._manifest({"pack/readme.md": b"x"})
+ with self.assertRaises(SkillUploadError):
+ _validate_manifest(manifest)
+
+ def test_rejects_oversized_file(self) -> None:
+ """A single part over the per-file limit is refused."""
+ manifest = UploadManifest.model_validate(
+ {
+ "entries": [
+ {"path": "pack/SKILL.md", "size": 1},
+ {"path": "pack/big.bin", "size": 10**12},
+ ],
+ },
+ )
+ with self.assertRaises(SkillUploadError):
+ _validate_manifest(manifest)
+
+ async def test_stream_round_trips(self) -> None:
+ """The emitted tar reads back with the same members."""
+ files = {
+ "pack/SKILL.md": _skill_md("gamma").encode("utf-8"),
+ "pack/lib/run.py": b"print('hi')",
+ }
+ manifest = self._manifest(files)
+ chunks = [
+ chunk
+ async for chunk in _tar_stream(manifest, self._uploads(files))
+ ]
+
+ archive = tarfile.open(fileobj=io.BytesIO(b"".join(chunks)))
+ self.assertEqual(
+ sorted(m.name for m in archive.getmembers()),
+ ["pack/SKILL.md", "pack/lib/run.py"],
+ )
+ member = archive.extractfile("pack/lib/run.py")
+ assert member is not None
+ self.assertEqual(member.read(), b"print('hi')")
+
+ async def test_declared_size_is_verified(self) -> None:
+ """A part longer than declared aborts the stream."""
+ manifest = UploadManifest.model_validate(
+ {"entries": [{"path": "pack/SKILL.md", "size": 2}]},
+ )
+ uploads = self._uploads({"pack/SKILL.md": b"much longer"})
+ with self.assertRaises(SkillUploadError):
+ async for _ in _tar_stream(manifest, uploads):
+ pass