Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(mcp): add built-in MCP server with per-workspace endpoints (#3371)

lyingbug76a19f14c4ae
diff --git a/client/mcp_endpoint.go b/client/mcp_endpoint.go
new file mode 100644
index 000000000..3b4c5540a
--- /dev/null
+++ b/client/mcp_endpoint.go
@@ -0,0 +1,164 @@
+package client
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+)
+
+// MCPEndpoint is one workspace-published MCP server endpoint that external
+// MCP clients connect to over Streamable HTTP at Path.
+type MCPEndpoint struct {
+ ID string `json:"id"`
+ TenantID uint64 `json:"tenant_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Enabled bool `json:"enabled"`
+ TokenHint string `json:"token_hint"`
+ KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
+ Tools []string `json:"tools"`
+ DefaultAgentID string `json:"default_agent_id"`
+ RateLimitPerMinute int `json:"rate_limit_per_minute"`
+ // Path is the public MCP path relative to the server origin (/mcp/<id>).
+ Path string `json:"path"`
+ LastUsedAt *string `json:"last_used_at,omitempty"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+ // Token is only present on create and rotate responses and is never
+ // returned again.
+ Token string `json:"token,omitempty"`
+}
+
+// MCPEndpointToolDefinition describes one tool an endpoint may expose.
+type MCPEndpointToolDefinition struct {
+ Name string `json:"name"`
+ Group string `json:"group"`
+ Destructive bool `json:"destructive"`
+}
+
+// MCPEndpointToolCatalog lists the tools an endpoint can expose.
+type MCPEndpointToolCatalog struct {
+ Groups []string `json:"groups"`
+ Tools []MCPEndpointToolDefinition `json:"tools"`
+ DefaultTools []string `json:"default_tools"`
+}
+
+// MCPEndpointRequest is the create/update payload. Nil pointers are omitted
+// so an update only touches the fields you set.
+type MCPEndpointRequest struct {
+ Name *string `json:"name,omitempty"`
+ Description *string `json:"description,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+ KnowledgeBaseIDs *[]string `json:"knowledge_base_ids,omitempty"`
+ Tools *[]string `json:"tools,omitempty"`
+ DefaultAgentID *string `json:"default_agent_id,omitempty"`
+ RateLimitPerMinute *int `json:"rate_limit_per_minute,omitempty"`
+}
+
+// ListMCPEndpoints lists the workspace's MCP endpoints (tokens are never included).
+func (c *Client) ListMCPEndpoints(ctx context.Context) ([]*MCPEndpoint, error) {
+ resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/mcp-endpoints", nil, nil)
+ if err != nil {
+ return nil, err
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Data []*MCPEndpoint `json:"data"`
+ }
+ if err := parseResponse(resp, &result); err != nil {
+ return nil, err
+ }
+ return result.Data, nil
+}
+
+// GetMCPEndpointToolCatalog returns the tools an endpoint may expose.
+func (c *Client) GetMCPEndpointToolCatalog(ctx context.Context) (*MCPEndpointToolCatalog, error) {
+ resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/mcp-endpoints/tools", nil, nil)
+ if err != nil {
+ return nil, err
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Data *MCPEndpointToolCatalog `json:"data"`
+ }
+ if err := parseResponse(resp, &result); err != nil {
+ return nil, err
+ }
+ return result.Data, nil
+}
+
+// CreateMCPEndpoint publishes a new endpoint. The returned Token is shown once.
+func (c *Client) CreateMCPEndpoint(ctx context.Context, req *MCPEndpointRequest) (*MCPEndpoint, error) {
+ resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/mcp-endpoints", req, nil)
+ if err != nil {
+ return nil, err
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Data *MCPEndpoint `json:"data"`
+ }
+ if err := parseResponse(resp, &result); err != nil {
+ return nil, err
+ }
+ return result.Data, nil
+}
+
+// GetMCPEndpoint returns one endpoint.
+func (c *Client) GetMCPEndpoint(ctx context.Context, endpointID string) (*MCPEndpoint, error) {
+ resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/mcp-endpoints/%s", endpointID), nil, nil)
+ if err != nil {
+ return nil, err
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Data *MCPEndpoint `json:"data"`
+ }
+ if err := parseResponse(resp, &result); err != nil {
+ return nil, err
+ }
+ return result.Data, nil
+}
+
+// UpdateMCPEndpoint applies a partial update; omitted fields are kept.
+func (c *Client) UpdateMCPEndpoint(
+ ctx context.Context, endpointID string, req *MCPEndpointRequest,
+) (*MCPEndpoint, error) {
+ resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/mcp-endpoints/%s", endpointID), req, nil)
+ if err != nil {
+ return nil, err
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Data *MCPEndpoint `json:"data"`
+ }
+ if err := parseResponse(resp, &result); err != nil {
+ return nil, err
+ }
+ return result.Data, nil
+}
+
+// DeleteMCPEndpoint deletes an endpoint; connected clients lose access immediately.
+func (c *Client) DeleteMCPEndpoint(ctx context.Context, endpointID string) error {
+ resp, err := c.doRequest(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/mcp-endpoints/%s", endpointID), nil, nil)
+ if err != nil {
+ return err
+ }
+ return parseResponse(resp, nil)
+}
+
+// RotateMCPEndpointToken replaces the bearer token. The new Token is shown once.
+func (c *Client) RotateMCPEndpointToken(ctx context.Context, endpointID string) (*MCPEndpoint, error) {
+ resp, err := c.doRequest(ctx, http.MethodPost,
+ fmt.Sprintf("/api/v1/mcp-endpoints/%s/rotate-token", endpointID), nil, nil)
+ if err != nil {
+ return nil, err
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Data *MCPEndpoint `json:"data"`
+ }
+ if err := parseResponse(resp, &result); err != nil {
+ return nil, err
+ }
+ return result.Data, nil
+}
diff --git a/docs/docs.go b/docs/docs.go
index 401360e12..ed4fb7a36 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -791,7 +791,7 @@ const docTemplate = `{
},
"/auth/auto-setup": {
"post": {
- "description": "Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程",
+ "description": "Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,首次及后续启动均须通过桌面原生凭据认证,免除手动注册/登录流程",
"consumes": [
"application/json"
],
@@ -5245,14 +5245,14 @@ const docTemplate = `{
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
},
- "403": {
- "description": "Forbidden",
+ "401": {
+ "description": "Unauthorized",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
},
- "401": {
- "description": "Unauthorized",
+ "403": {
+ "description": "Forbidden",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -8333,6 +8333,303 @@ const docTemplate = `{
}
}
},
+ "/mcp-endpoints": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "获取 MCP 端点列表",
+ "responses": {
+ "200": {
+ "description": "端点列表",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "为当前工作空间发布一个 MCP 端点,响应中的 token 只返回一次",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "创建 MCP 端点",
+ "parameters": [
+ {
+ "description": "端点配置:name、description、enabled、knowledge_base_ids、tools 等",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "创建的端点,含一次性 token",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/mcp-endpoints/tools": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "返回工作空间 MCP 端点可勾选的工具清单、分组和默认勾选项",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "获取 MCP 端点工具目录",
+ "responses": {
+ "200": {
+ "description": "工具目录",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/mcp-endpoints/{endpoint_id}": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "获取 MCP 端点详情",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "端点详情",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "put": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "更新 MCP 端点",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "要更新的字段,未提供的字段保持不变",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "更新后的端点",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "删除 MCP 端点",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "删除成功",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/mcp-endpoints/{endpoint_id}/rotate-token": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "生成新令牌并立即作废旧令牌,响应中的 token 只返回一次",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "轮换 MCP 端点令牌",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "含新 token 的端点",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
"/mcp-services": {
"get": {
"security": [
@@ -8343,7 +8640,7 @@ const docTemplate = `{
"ApiKeyAuth": []
}
],
- "description": "获取当前空间的所有MCP服务",
+ "description": "获取当前空间的所有MCP服务(含已保存工具目录数量)",
"consumes": [
"application/json"
],
@@ -11560,14 +11857,13 @@ const docTemplate = `{
"Bearer": []
}
],
- "description": "按空间名搜索可邀请的空间(排除已加入的空间)用于邀请加入组织;按空间去重",
"produces": [
"application/json"
],
"tags": [
"组织管理"
],
- "summary": "搜索可邀请的空间",
+ "summary": "Resolve a workspace ID for invitation",
"parameters": [
{
"type": "string",
@@ -11578,17 +11874,10 @@ const docTemplate = `{
},
{
"type": "string",
- "description": "搜索关键词(空间名)",
+ "description": "Exact workspace ID",
"name": "q",
"in": "query",
"required": true
- },
- {
- "type": "integer",
- "default": 10,
- "description": "返回数量限制",
- "name": "limit",
- "in": "query"
}
],
"responses": {
@@ -11598,12 +11887,6 @@ const docTemplate = `{
"type": "object",
"additionalProperties": true
}
- },
- "403": {
- "description": "Forbidden",
- "schema": {
- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
- }
}
}
}
@@ -13131,28 +13414,179 @@ const docTemplate = `{
"parameters": [
{
"type": "string",
- "description": "会话ID",
- "name": "id",
+ "description": "会话ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "清空成功",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "404": {
+ "description": "会话不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{id}/pin": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "取消指定会话的置顶",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "会话"
+ ],
+ "summary": "取消置顶会话",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "取消置顶成功",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "会话不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{id}/steer": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "刷新页面后用来恢复输入框上方的队列。没有正在运行的 turn 时返回空列表。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "列出当前运行中尚未消费的排队消息",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "503": {
+ "description": "活 turn 查询失败,可重试",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{id}/steer/{steer_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "从当前运行的排队列表里去掉一条,不再注入也不再作为 follow-up 发出。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "删除一条排队中的消息",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "排队消息 ID",
+ "name": "steer_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
- "description": "清空成功",
+ "description": "OK",
"schema": {
"type": "object",
"additionalProperties": true
}
},
- "400": {
- "description": "请求参数错误",
+ "404": {
+ "description": "Not Found",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
},
- "404": {
- "description": "会话不存在",
+ "503": {
+ "description": "活 turn 查询失败,可重试",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -13160,43 +13594,40 @@ const docTemplate = `{
}
}
},
- "/sessions/{id}/pin": {
- "delete": {
+ "/sessions/{session_id}/artifacts": {
+ "get": {
"security": [
{
"Bearer": []
- },
- {
- "ApiKeyAuth": []
}
],
- "description": "取消指定会话的置顶",
+ "description": "返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)",
"produces": [
"application/json"
],
"tags": [
"会话"
],
- "summary": "取消置顶会话",
+ "summary": "列出会话生成的产物文件",
"parameters": [
{
"type": "string",
"description": "会话ID",
- "name": "id",
+ "name": "session_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
- "description": "取消置顶成功",
+ "description": "OK",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"404": {
- "description": "会话不存在",
+ "description": "Not Found",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -13204,40 +13635,67 @@ const docTemplate = `{
}
}
},
- "/sessions/{session_id}/artifacts": {
- "get": {
+ "/sessions/{session_id}/fork": {
+ "post": {
"security": [
{
"Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
}
],
- "description": "返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)",
+ "description": "从指定的用户或助手消息处分叉出一个新会话。用户消息:复制其之前的历史并预填该问题;助手消息:复制含该回答在内的历史,从该轮沙箱状态继续。",
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"会话"
],
- "summary": "列出会话生成的产物文件",
+ "summary": "分叉会话",
"parameters": [
{
"type": "string",
- "description": "会话ID",
+ "description": "源会话 ID",
"name": "session_id",
"in": "path",
"required": true
+ },
+ {
+ "description": "分叉请求",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler_session.ForkSessionRequest"
+ }
}
],
"responses": {
"200": {
- "description": "OK",
+ "description": "新会话",
"schema": {
"type": "object",
"additionalProperties": true
}
},
+ "400": {
+ "description": "请求参数错误 / 分叉点角色不支持",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
"404": {
- "description": "Not Found",
+ "description": "会话或消息不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "409": {
+ "description": "源会话正在生成中",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -13404,6 +13862,137 @@ const docTemplate = `{
}
}
},
+ "/sessions/{session_id}/steer": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "向运行中的 agent turn 追加用户消息(after 排队 / inject 注入)。无活 turn 时返回 new_run。",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "向运行中的对话追加消息",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "session_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "追加消息",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler_session.SteerMessageRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "queued | new_run",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "404": {
+ "description": "会话不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "503": {
+ "description": "活 turn 查询失败,可重试",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{session_id}/steer/{steer_id}/inject": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "把一条 delivery=after 的排队消息改为 inject,运行中的 agent 会在下一轮边界读到它。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "将排队消息改为立即注入",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "session_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "排队消息 ID",
+ "name": "steer_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "queued | new_run",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "503": {
+ "description": "活 turn 查询失败,可重试",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/sessions/{session_id}/stop": {
"post": {
"security": [
@@ -17714,6 +18303,10 @@ const docTemplate = `{
"github_com_Tencent_WeKnora_internal_types.AgentStep": {
"type": "object",
"properties": {
+ "intermediate_answer": {
+ "description": "IntermediateAnswer preserves a plain answer followed by a loop-end steer.\nThe canonical final answer is still stored in Message.Content.",
+ "type": "boolean"
+ },
"iteration": {
"description": "Iteration number (0-indexed)",
"type": "integer"
@@ -17736,6 +18329,13 @@ const docTemplate = `{
"items": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall"
}
+ },
+ "user_messages_before": {
+ "description": "UserMessagesBefore records consumed steer rows in delivery order, before\nthis model response. Unlike timestamps, this remains unambiguous on replay.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
@@ -18350,7 +18950,7 @@ const docTemplate = `{
"type": "string"
},
"context_template_id": {
- "description": "ContextTemplateID references a template ID in prompt_templates/ YAML files.\nIf set and ContextTemplate is empty, the template content will be resolved at startup.",
+ "description": "ContextTemplateID references a template ID in prompt_templates/ YAML files.\nIf set and ContextTemplate is empty, the template content is resolved at request time for saved agents.",
"type": "string"
},
"data_analysis_enabled": {
@@ -18533,7 +19133,7 @@ const docTemplate = `{
"type": "string"
},
"system_prompt_id": {
- "description": "SystemPromptID references a template ID in prompt_templates/ YAML files.\nIf set and SystemPrompt is empty, the template content will be resolved at startup.",
+ "description": "SystemPromptID references a template ID in prompt_templates/ YAML files.\nIf set and SystemPrompt is empty, the template content is resolved at request time for saved agents.",
"type": "string"
},
"temperature": {
@@ -19665,6 +20265,10 @@ const docTemplate = `{
"question_generation_config": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig"
},
+ "summary_enabled": {
+ "description": "SummaryEnabled defaults to true when omitted for backward compatibility.",
+ "type": "boolean"
+ },
"vlm_config": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig"
}
@@ -20242,6 +20846,14 @@ const docTemplate = `{
"description": "Message role: \"user\", \"assistant\", \"system\"",
"type": "string"
},
+ "sandbox_checkpoint": {
+ "description": "SandboxCheckpoint is the git commit this assistant turn produced in the\nsession sandbox's /workspace. Nil for user messages, for turns that ran\nwithout a sandbox, and for turns whose commit failed (best-effort — a\nfailed checkpoint must never block the reply). A message without a\ncheckpoint cannot serve as a fork point with sandbox state.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SandboxCheckpoint"
+ }
+ ]
+ },
"session_id": {
"description": "ID of the session this message belongs to",
"type": "string"
@@ -20270,6 +20882,10 @@ const docTemplate = `{
"github_com_Tencent_WeKnora_internal_types.MessageArtifact": {
"type": "object",
"properties": {
+ "content_hash": {
+ "description": "SHA-256 of the persisted bytes",
+ "type": "string"
+ },
"created_at": {
"description": "When WeKnora persisted the blob",
"type": "string"
@@ -21421,6 +22037,20 @@ const docTemplate = `{
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.SandboxCheckpoint": {
+ "type": "object",
+ "properties": {
+ "commit_sha": {
+ "type": "string"
+ },
+ "committed_at": {
+ "type": "string"
+ },
+ "sandbox_id": {
+ "type": "string"
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.SandboxNetworkPolicy": {
"type": "object",
"properties": {
@@ -21648,6 +22278,10 @@ const docTemplate = `{
"description": "Description",
"type": "string"
},
+ "forked_from_message_id": {
+ "description": "ForkedFromMessageID is the user or assistant message, IN THE PARENT\nSESSION, that the fork branched at. For a user point, messages strictly\nbefore it were copied here. For an assistant point, that answer is\nincluded so the branch continues after it.",
+ "type": "string"
+ },
"id": {
"description": "ID",
"type": "string"
@@ -21668,6 +22302,10 @@ const docTemplate = `{
}
]
},
+ "parent_session_id": {
+ "description": "ParentSessionID names the session this one was forked from. Empty for\nordinary sessions. Deliberately not a foreign key: the parent may be\ndeleted while the branch lives on, and a branch must not cascade away\nwith it. A dangling value simply renders as an ordinary session.",
+ "type": "string"
+ },
"pinned_at": {
"description": "PinnedAt records when the session was pinned; nil when not pinned.",
"type": "string"
@@ -21714,6 +22352,9 @@ const docTemplate = `{
"type": "string"
}
},
+ "local_browser_enabled": {
+ "type": "boolean"
+ },
"mcp_service_ids": {
"type": "array",
"items": {
@@ -22284,6 +22925,10 @@ const docTemplate = `{
"description": "DefaultTimeoutSec is the per-execution timeout in seconds. 0 uses the\nprogram's built-in default.",
"type": "integer"
},
+ "desktop_enabled": {
+ "description": "DesktopEnabled declares that this config's base template is a desktop\nimage (XFCE + x11vnc + websockify). It is NOT a second template: a\nconfig has exactly one boot target, and skill snapshots stack on top of\nthis base generation after generation. Flipping it changes the base, so\nany installed skills must be rebuilt from the new one.",
+ "type": "boolean"
+ },
"docker": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DockerSandboxConfig"
},
@@ -22322,7 +22967,7 @@ const docTemplate = `{
"type": "string"
},
"terminal_idle_disconnect_sec": {
- "description": "TerminalIdleDisconnectSec is how long an interactive terminal may go\nwithout keystrokes or PTY output before WeKnora closes the connection\nso the sandbox can pause on its provider TTL. 0 uses the built-in\ndefault (15 minutes). Not an identity field.",
+ "description": "TerminalIdleDisconnectSec is how long an interactive terminal or\ndesktop may go without user activity before WeKnora closes the\nconnection so the sandbox can pause on its provider TTL. Terminal\ncounts keystrokes and PTY output; desktop counts mouse and keyboard.\n0 uses the built-in default (15 minutes). Not an identity field.",
"type": "integer"
},
"volume_mount": {
@@ -22654,6 +23299,10 @@ const docTemplate = `{
"github_com_Tencent_WeKnora_internal_types.UserPreferences": {
"type": "object",
"properties": {
+ "browser_search_instructions": {
+ "description": "BrowserSearchInstructions customizes browser search for this user. Nil/empty uses the platform default.",
+ "type": "string"
+ },
"last_active_tenant_id": {
"description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Written by the SPA's preferences\nPUT and by service-level SwitchTenant (including when switching\nhome, which stores the home ID). Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome. Refresh JWT claims have no tenant_id, so RefreshToken\nre-resolves from this field.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.",
"type": "integer"
@@ -24958,6 +25607,7 @@ const docTemplate = `{
"type": "object",
"properties": {
"avatar": {
+ "description": "Avatar travels as a pointer so an omitted field can be told apart from\nan explicit clear: nil keeps the stored avatar, a pointer to \"\" wipes\nit. As a plain string the two cases were indistinguishable, so a caller\nthat PUT only a config silently zeroed the avatar and still got a 200.",
"type": "string"
},
"config": {
@@ -25427,6 +26077,10 @@ const docTemplate = `{
"internal_handler.updateMyPreferencesRequest": {
"type": "object",
"properties": {
+ "browser_search_instructions": {
+ "type": "string",
+ "maxLength": 4000
+ },
"last_active_tenant_id": {
"description": "LastActiveTenantID lets clients persist \"after a fresh login,\ndrop me back into this workspace\" across devices. The SPA sends\nthis after every tenant switch; POST /auth/switch-tenant records\nthe same preference server-side. Send a positive workspace id to\nset / replace, or 0 to clear. Membership is validated at next\nlogin, not here. Nil = field omitted from the PATCH and stays\nuntouched.",
"type": "integer"
@@ -25511,6 +26165,10 @@ const docTemplate = `{
"type": "string"
}
},
+ "local_browser_enabled": {
+ "description": "Browser source",
+ "type": "boolean"
+ },
"mcp_service_ids": {
"description": "Per-request MCP services selected via @mention",
"type": "array",
@@ -25569,6 +26227,22 @@ const docTemplate = `{
}
}
},
+ "internal_handler_session.ForkSessionRequest": {
+ "type": "object",
+ "required": [
+ "message_id"
+ ],
+ "properties": {
+ "message_id": {
+ "description": "MessageID is the message to branch at. A user message copies history\nstrictly before it (the client prefills that question). An assistant\nmessage copies history through that answer so the branch continues after it.",
+ "type": "string"
+ },
+ "title": {
+ "description": "Title is optional. Empty falls back to the source title plus a suffix.",
+ "type": "string"
+ }
+ }
+ },
"internal_handler_session.GenerateTitleRequest": {
"type": "object",
"required": [
@@ -25680,6 +26354,37 @@ const docTemplate = `{
}
}
},
+ "internal_handler_session.SteerMessageRequest": {
+ "type": "object",
+ "required": [
+ "query"
+ ],
+ "properties": {
+ "channel": {
+ "type": "string"
+ },
+ "delivery": {
+ "description": "Delivery is \"after\" (default) or \"inject\". See the constants above.",
+ "type": "string"
+ },
+ "expected_assistant_message_id": {
+ "description": "Optional for older clients. New clients pin delivery to the run they see\nand supply a stable ID so a consume event may precede the HTTP response.",
+ "type": "string"
+ },
+ "mentioned_items": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/internal_handler_session.MentionedItemRequest"
+ }
+ },
+ "query": {
+ "type": "string"
+ },
+ "steer_id": {
+ "type": "string"
+ }
+ }
+ },
"internal_handler_session.StopSessionRequest": {
"type": "object",
"required": [
diff --git a/docs/swagger.json b/docs/swagger.json
index 170fab224..9e00f227d 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -784,7 +784,7 @@
},
"/auth/auto-setup": {
"post": {
- "description": "Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程",
+ "description": "Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,首次及后续启动均须通过桌面原生凭据认证,免除手动注册/登录流程",
"consumes": [
"application/json"
],
@@ -5238,14 +5238,14 @@
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
},
- "403": {
- "description": "Forbidden",
+ "401": {
+ "description": "Unauthorized",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
},
- "401": {
- "description": "Unauthorized",
+ "403": {
+ "description": "Forbidden",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -8326,6 +8326,303 @@
}
}
},
+ "/mcp-endpoints": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "获取 MCP 端点列表",
+ "responses": {
+ "200": {
+ "description": "端点列表",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "为当前工作空间发布一个 MCP 端点,响应中的 token 只返回一次",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "创建 MCP 端点",
+ "parameters": [
+ {
+ "description": "端点配置:name、description、enabled、knowledge_base_ids、tools 等",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "创建的端点,含一次性 token",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/mcp-endpoints/tools": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "返回工作空间 MCP 端点可勾选的工具清单、分组和默认勾选项",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "获取 MCP 端点工具目录",
+ "responses": {
+ "200": {
+ "description": "工具目录",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/mcp-endpoints/{endpoint_id}": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "获取 MCP 端点详情",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "端点详情",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "put": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "更新 MCP 端点",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "要更新的字段,未提供的字段保持不变",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "更新后的端点",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "删除 MCP 端点",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "删除成功",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/mcp-endpoints/{endpoint_id}/rotate-token": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "生成新令牌并立即作废旧令牌,响应中的 token 只返回一次",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP端点"
+ ],
+ "summary": "轮换 MCP 端点令牌",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "端点 ID",
+ "name": "endpoint_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "含新 token 的端点",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "端点不存在",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
"/mcp-services": {
"get": {
"security": [
@@ -8336,7 +8633,7 @@
"ApiKeyAuth": []
}
],
- "description": "获取当前空间的所有MCP服务",
+ "description": "获取当前空间的所有MCP服务(含已保存工具目录数量)",
"consumes": [
"application/json"
],
@@ -11553,14 +11850,13 @@
"Bearer": []
}
],
- "description": "按空间名搜索可邀请的空间(排除已加入的空间)用于邀请加入组织;按空间去重",
"produces": [
"application/json"
],
"tags": [
"组织管理"
],
- "summary": "搜索可邀请的空间",
+ "summary": "Resolve a workspace ID for invitation",
"parameters": [
{
"type": "string",
@@ -11571,17 +11867,10 @@
},
{
"type": "string",
- "description": "搜索关键词(空间名)",
+ "description": "Exact workspace ID",
"name": "q",
"in": "query",
"required": true
- },
- {
- "type": "integer",
- "default": 10,
- "description": "返回数量限制",
- "name": "limit",
- "in": "query"
}
],
"responses": {
@@ -11591,12 +11880,6 @@
"type": "object",
"additionalProperties": true
}
- },
- "403": {
- "description": "Forbidden",
- "schema": {
- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
- }
}
}
}
@@ -13124,28 +13407,179 @@
"parameters": [
{
"type": "string",
- "description": "会话ID",
- "name": "id",
+ "description": "会话ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "清空成功",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "404": {
+ "description": "会话不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{id}/pin": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "取消指定会话的置顶",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "会话"
+ ],
+ "summary": "取消置顶会话",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "取消置顶成功",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "会话不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{id}/steer": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "刷新页面后用来恢复输入框上方的队列。没有正在运行的 turn 时返回空列表。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "列出当前运行中尚未消费的排队消息",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "503": {
+ "description": "活 turn 查询失败,可重试",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{id}/steer/{steer_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "从当前运行的排队列表里去掉一条,不再注入也不再作为 follow-up 发出。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "删除一条排队中的消息",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "排队消息 ID",
+ "name": "steer_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
- "description": "清空成功",
+ "description": "OK",
"schema": {
"type": "object",
"additionalProperties": true
}
},
- "400": {
- "description": "请求参数错误",
+ "404": {
+ "description": "Not Found",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
},
- "404": {
- "description": "会话不存在",
+ "503": {
+ "description": "活 turn 查询失败,可重试",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -13153,43 +13587,40 @@
}
}
},
- "/sessions/{id}/pin": {
- "delete": {
+ "/sessions/{session_id}/artifacts": {
+ "get": {
"security": [
{
"Bearer": []
- },
- {
- "ApiKeyAuth": []
}
],
- "description": "取消指定会话的置顶",
+ "description": "返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)",
"produces": [
"application/json"
],
"tags": [
"会话"
],
- "summary": "取消置顶会话",
+ "summary": "列出会话生成的产物文件",
"parameters": [
{
"type": "string",
"description": "会话ID",
- "name": "id",
+ "name": "session_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
- "description": "取消置顶成功",
+ "description": "OK",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"404": {
- "description": "会话不存在",
+ "description": "Not Found",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -13197,40 +13628,67 @@
}
}
},
- "/sessions/{session_id}/artifacts": {
- "get": {
+ "/sessions/{session_id}/fork": {
+ "post": {
"security": [
{
"Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
}
],
- "description": "返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)",
+ "description": "从指定的用户或助手消息处分叉出一个新会话。用户消息:复制其之前的历史并预填该问题;助手消息:复制含该回答在内的历史,从该轮沙箱状态继续。",
+ "consumes": [
+ "application/json"
+ ],
"produces": [
"application/json"
],
"tags": [
"会话"
],
- "summary": "列出会话生成的产物文件",
+ "summary": "分叉会话",
"parameters": [
{
"type": "string",
- "description": "会话ID",
+ "description": "源会话 ID",
"name": "session_id",
"in": "path",
"required": true
+ },
+ {
+ "description": "分叉请求",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler_session.ForkSessionRequest"
+ }
}
],
"responses": {
"200": {
- "description": "OK",
+ "description": "新会话",
"schema": {
"type": "object",
"additionalProperties": true
}
},
+ "400": {
+ "description": "请求参数错误 / 分叉点角色不支持",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
"404": {
- "description": "Not Found",
+ "description": "会话或消息不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "409": {
+ "description": "源会话正在生成中",
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
@@ -13397,6 +13855,137 @@
}
}
},
+ "/sessions/{session_id}/steer": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "向运行中的 agent turn 追加用户消息(after 排队 / inject 注入)。无活 turn 时返回 new_run。",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "向运行中的对话追加消息",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "session_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "追加消息",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler_session.SteerMessageRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "queued | new_run",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "404": {
+ "description": "会话不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "503": {
+ "description": "活 turn 查询失败,可重试",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/sessions/{session_id}/steer/{steer_id}/inject": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "把一条 delivery=after 的排队消息改为 inject,运行中的 agent 会在下一轮边界读到它。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "问答"
+ ],
+ "summary": "将排队消息改为立即注入",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "会话 ID",
+ "name": "session_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "排队消息 ID",
+ "name": "steer_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "queued | new_run",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "503": {
+ "description": "活 turn 查询失败,可重试",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/sessions/{session_id}/stop": {
"post": {
"security": [
@@ -17707,6 +18296,10 @@
"github_com_Tencent_WeKnora_internal_types.AgentStep": {
"type": "object",
"properties": {
+ "intermediate_answer": {
+ "description": "IntermediateAnswer preserves a plain answer followed by a loop-end steer.\nThe canonical final answer is still stored in Message.Content.",
+ "type": "boolean"
+ },
"iteration": {
"description": "Iteration number (0-indexed)",
"type": "integer"
@@ -17729,6 +18322,13 @@
"items": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall"
}
+ },
+ "user_messages_before": {
+ "description": "UserMessagesBefore records consumed steer rows in delivery order, before\nthis model response. Unlike timestamps, this remains unambiguous on replay.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
@@ -18343,7 +18943,7 @@
"type": "string"
},
"context_template_id": {
- "description": "ContextTemplateID references a template ID in prompt_templates/ YAML files.\nIf set and ContextTemplate is empty, the template content will be resolved at startup.",
+ "description": "ContextTemplateID references a template ID in prompt_templates/ YAML files.\nIf set and ContextTemplate is empty, the template content is resolved at request time for saved agents.",
"type": "string"
},
"data_analysis_enabled": {
@@ -18526,7 +19126,7 @@
"type": "string"
},
"system_prompt_id": {
- "description": "SystemPromptID references a template ID in prompt_templates/ YAML files.\nIf set and SystemPrompt is empty, the template content will be resolved at startup.",
+ "description": "SystemPromptID references a template ID in prompt_templates/ YAML files.\nIf set and SystemPrompt is empty, the template content is resolved at request time for saved agents.",
"type": "string"
},
"temperature": {
@@ -19658,6 +20258,10 @@
"question_generation_config": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig"
},
+ "summary_enabled": {
+ "description": "SummaryEnabled defaults to true when omitted for backward compatibility.",
+ "type": "boolean"
+ },
"vlm_config": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig"
}
@@ -20235,6 +20839,14 @@
"description": "Message role: \"user\", \"assistant\", \"system\"",
"type": "string"
},
+ "sandbox_checkpoint": {
+ "description": "SandboxCheckpoint is the git commit this assistant turn produced in the\nsession sandbox's /workspace. Nil for user messages, for turns that ran\nwithout a sandbox, and for turns whose commit failed (best-effort — a\nfailed checkpoint must never block the reply). A message without a\ncheckpoint cannot serve as a fork point with sandbox state.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SandboxCheckpoint"
+ }
+ ]
+ },
"session_id": {
"description": "ID of the session this message belongs to",
"type": "string"
@@ -20263,6 +20875,10 @@
"github_com_Tencent_WeKnora_internal_types.MessageArtifact": {
"type": "object",
"properties": {
+ "content_hash": {
+ "description": "SHA-256 of the persisted bytes",
+ "type": "string"
+ },
"created_at": {
"description": "When WeKnora persisted the blob",
"type": "string"
@@ -21414,6 +22030,20 @@
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.SandboxCheckpoint": {
+ "type": "object",
+ "properties": {
+ "commit_sha": {
+ "type": "string"
+ },
+ "committed_at": {
+ "type": "string"
+ },
+ "sandbox_id": {
+ "type": "string"
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.SandboxNetworkPolicy": {
"type": "object",
"properties": {
@@ -21641,6 +22271,10 @@
"description": "Description",
"type": "string"
},
+ "forked_from_message_id": {
+ "description": "ForkedFromMessageID is the user or assistant message, IN THE PARENT\nSESSION, that the fork branched at. For a user point, messages strictly\nbefore it were copied here. For an assistant point, that answer is\nincluded so the branch continues after it.",
+ "type": "string"
+ },
"id": {
"description": "ID",
"type": "string"
@@ -21661,6 +22295,10 @@
}
]
},
+ "parent_session_id": {
+ "description": "ParentSessionID names the session this one was forked from. Empty for\nordinary sessions. Deliberately not a foreign key: the parent may be\ndeleted while the branch lives on, and a branch must not cascade away\nwith it. A dangling value simply renders as an ordinary session.",
+ "type": "string"
+ },
"pinned_at": {
"description": "PinnedAt records when the session was pinned; nil when not pinned.",
"type": "string"
@@ -21707,6 +22345,9 @@
"type": "string"
}
},
+ "local_browser_enabled": {
+ "type": "boolean"
+ },
"mcp_service_ids": {
"type": "array",
"items": {
@@ -22277,6 +22918,10 @@
"description": "DefaultTimeoutSec is the per-execution timeout in seconds. 0 uses the\nprogram's built-in default.",
"type": "integer"
},
+ "desktop_enabled": {
+ "description": "DesktopEnabled declares that this config's base template is a desktop\nimage (XFCE + x11vnc + websockify). It is NOT a second template: a\nconfig has exactly one boot target, and skill snapshots stack on top of\nthis base generation after generation. Flipping it changes the base, so\nany installed skills must be rebuilt from the new one.",
+ "type": "boolean"
+ },
"docker": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DockerSandboxConfig"
},
@@ -22315,7 +22960,7 @@
"type": "string"
},
"terminal_idle_disconnect_sec": {
- "description": "TerminalIdleDisconnectSec is how long an interactive terminal may go\nwithout keystrokes or PTY output before WeKnora closes the connection\nso the sandbox can pause on its provider TTL. 0 uses the built-in\ndefault (15 minutes). Not an identity field.",
+ "description": "TerminalIdleDisconnectSec is how long an interactive terminal or\ndesktop may go without user activity before WeKnora closes the\nconnection so the sandbox can pause on its provider TTL. Terminal\ncounts keystrokes and PTY output; desktop counts mouse and keyboard.\n0 uses the built-in default (15 minutes). Not an identity field.",
"type": "integer"
},
"volume_mount": {
@@ -22647,6 +23292,10 @@
"github_com_Tencent_WeKnora_internal_types.UserPreferences": {
"type": "object",
"properties": {
+ "browser_search_instructions": {
+ "description": "BrowserSearchInstructions customizes browser search for this user. Nil/empty uses the platform default.",
+ "type": "string"
+ },
"last_active_tenant_id": {
"description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Written by the SPA's preferences\nPUT and by service-level SwitchTenant (including when switching\nhome, which stores the home ID). Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome. Refresh JWT claims have no tenant_id, so RefreshToken\nre-resolves from this field.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.",
"type": "integer"
@@ -24951,6 +25600,7 @@
"type": "object",
"properties": {
"avatar": {
+ "description": "Avatar travels as a pointer so an omitted field can be told apart from\nan explicit clear: nil keeps the stored avatar, a pointer to \"\" wipes\nit. As a plain string the two cases were indistinguishable, so a caller\nthat PUT only a config silently zeroed the avatar and still got a 200.",
"type": "string"
},
"config": {
@@ -25420,6 +26070,10 @@
"internal_handler.updateMyPreferencesRequest": {
"type": "object",
"properties": {
+ "browser_search_instructions": {
+ "type": "string",
+ "maxLength": 4000
+ },
"last_active_tenant_id": {
"description": "LastActiveTenantID lets clients persist \"after a fresh login,\ndrop me back into this workspace\" across devices. The SPA sends\nthis after every tenant switch; POST /auth/switch-tenant records\nthe same preference server-side. Send a positive workspace id to\nset / replace, or 0 to clear. Membership is validated at next\nlogin, not here. Nil = field omitted from the PATCH and stays\nuntouched.",
"type": "integer"
@@ -25504,6 +26158,10 @@
"type": "string"
}
},
+ "local_browser_enabled": {
+ "description": "Browser source",
+ "type": "boolean"
+ },
"mcp_service_ids": {
"description": "Per-request MCP services selected via @mention",
"type": "array",
@@ -25562,6 +26220,22 @@
}
}
},
+ "internal_handler_session.ForkSessionRequest": {
+ "type": "object",
+ "required": [
+ "message_id"
+ ],
+ "properties": {
+ "message_id": {
+ "description": "MessageID is the message to branch at. A user message copies history\nstrictly before it (the client prefills that question). An assistant\nmessage copies history through that answer so the branch continues after it.",
+ "type": "string"
+ },
+ "title": {
+ "description": "Title is optional. Empty falls back to the source title plus a suffix.",
+ "type": "string"
+ }
+ }
+ },
"internal_handler_session.GenerateTitleRequest": {
"type": "object",
"required": [
@@ -25673,6 +26347,37 @@
}
}
},
+ "internal_handler_session.SteerMessageRequest": {
+ "type": "object",
+ "required": [
+ "query"
+ ],
+ "properties": {
+ "channel": {
+ "type": "string"
+ },
+ "delivery": {
+ "description": "Delivery is \"after\" (default) or \"inject\". See the constants above.",
+ "type": "string"
+ },
+ "expected_assistant_message_id": {
+ "description": "Optional for older clients. New clients pin delivery to the run they see\nand supply a stable ID so a consume event may precede the HTTP response.",
+ "type": "string"
+ },
+ "mentioned_items": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/internal_handler_session.MentionedItemRequest"
+ }
+ },
+ "query": {
+ "type": "string"
+ },
+ "steer_id": {
+ "type": "string"
+ }
+ }
+ },
"internal_handler_session.StopSessionRequest": {
"type": "object",
"required": [
@@ -25713,4 +26418,4 @@
"in": "header"
}
}
-}
+}
\ No newline at end of file
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index 35975aae0..f4c15ebd4 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -258,6 +258,11 @@ definitions:
type: object
github_com_Tencent_WeKnora_internal_types.AgentStep:
properties:
+ intermediate_answer:
+ description: |-
+ IntermediateAnswer preserves a plain answer followed by a loop-end steer.
+ The canonical final answer is still stored in Message.Content.
+ type: boolean
iteration:
description: Iteration number (0-indexed)
type: integer
@@ -279,6 +284,13 @@ definitions:
items:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall'
type: array
+ user_messages_before:
+ description: |-
+ UserMessagesBefore records consumed steer rows in delivery order, before
+ this model response. Unlike timestamps, this remains unambiguous on replay.
+ items:
+ type: string
+ type: array
type: object
github_com_Tencent_WeKnora_internal_types.AnswerStrategy:
enum:
@@ -829,7 +841,7 @@ definitions:
context_template_id:
description: |-
ContextTemplateID references a template ID in prompt_templates/ YAML files.
- If set and ContextTemplate is empty, the template content will be resolved at startup.
+ If set and ContextTemplate is empty, the template content is resolved at request time for saved agents.
type: string
data_analysis_enabled:
description: |-
@@ -1030,7 +1042,7 @@ definitions:
system_prompt_id:
description: |-
SystemPromptID references a template ID in prompt_templates/ YAML files.
- If set and SystemPrompt is empty, the template content will be resolved at startup.
+ If set and SystemPrompt is empty, the template content is resolved at request time for saved agents.
type: string
temperature:
description: Temperature for LLM (0-1)
@@ -1886,6 +1898,9 @@ definitions:
type: array
question_generation_config:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig'
+ summary_enabled:
+ description: SummaryEnabled defaults to true when omitted for backward compatibility.
+ type: boolean
vlm_config:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig'
type: object
@@ -2362,6 +2377,15 @@ definitions:
role:
description: 'Message role: "user", "assistant", "system"'
type: string
+ sandbox_checkpoint:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SandboxCheckpoint'
+ description: |-
+ SandboxCheckpoint is the git commit this assistant turn produced in the
+ session sandbox's /workspace. Nil for user messages, for turns that ran
+ without a sandbox, and for turns whose commit failed (best-effort — a
+ failed checkpoint must never block the reply). A message without a
+ checkpoint cannot serve as a fork point with sandbox state.
session_id:
description: ID of the session this message belongs to
type: string
@@ -2387,6 +2411,9 @@ definitions:
type: object
github_com_Tencent_WeKnora_internal_types.MessageArtifact:
properties:
+ content_hash:
+ description: SHA-256 of the persisted bytes
+ type: string
created_at:
description: When WeKnora persisted the blob
type: string
@@ -3261,6 +3288,15 @@ definitions:
use_ssl:
type: boolean
type: object
+ github_com_Tencent_WeKnora_internal_types.SandboxCheckpoint:
+ properties:
+ commit_sha:
+ type: string
+ committed_at:
+ type: string
+ sandbox_id:
+ type: string
+ type: object
github_com_Tencent_WeKnora_internal_types.SandboxNetworkPolicy:
properties:
allow_out:
@@ -3453,6 +3489,13 @@ definitions:
description:
description: Description
type: string
+ forked_from_message_id:
+ description: |-
+ ForkedFromMessageID is the user or assistant message, IN THE PARENT
+ SESSION, that the fork branched at. For a user point, messages strictly
+ before it were copied here. For an assistant point, that answer is
+ included so the branch continues after it.
+ type: string
id:
description: ID
type: string
@@ -3476,6 +3519,13 @@ definitions:
that reopening the session can restore the original request context to
the chat UI. Stored in the legacy sessions.agent_config JSONB column to
avoid a new migration; the shape used today is `SessionLastRequestState`.
+ parent_session_id:
+ description: |-
+ ParentSessionID names the session this one was forked from. Empty for
+ ordinary sessions. Deliberately not a foreign key: the parent may be
+ deleted while the branch lives on, and a branch must not cascade away
+ with it. A dangling value simply renders as an ordinary session.
+ type: string
pinned_at:
description: PinnedAt records when the session was pinned; nil when not pinned.
type: string
@@ -3517,6 +3567,8 @@ definitions:
items:
type: string
type: array
+ local_browser_enabled:
+ type: boolean
mcp_service_ids:
items:
type: string
@@ -3942,6 +3994,14 @@ definitions:
DefaultTimeoutSec is the per-execution timeout in seconds. 0 uses the
program's built-in default.
type: integer
+ desktop_enabled:
+ description: |-
+ DesktopEnabled declares that this config's base template is a desktop
+ image (XFCE + x11vnc + websockify). It is NOT a second template: a
+ config has exactly one boot target, and skill snapshots stack on top of
+ this base generation after generation. Flipping it changes the base, so
+ any installed skills must be rebuilt from the new one.
+ type: boolean
docker:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.DockerSandboxConfig'
e2b:
@@ -3984,10 +4044,11 @@ definitions:
type: string
terminal_idle_disconnect_sec:
description: |-
- TerminalIdleDisconnectSec is how long an interactive terminal may go
- without keystrokes or PTY output before WeKnora closes the connection
- so the sandbox can pause on its provider TTL. 0 uses the built-in
- default (15 minutes). Not an identity field.
+ TerminalIdleDisconnectSec is how long an interactive terminal or
+ desktop may go without user activity before WeKnora closes the
+ connection so the sandbox can pause on its provider TTL. Terminal
+ counts keystrokes and PTY output; desktop counts mouse and keyboard.
+ 0 uses the built-in default (15 minutes). Not an identity field.
type: integer
volume_mount:
allOf:
@@ -4218,6 +4279,10 @@ definitions:
type: object
github_com_Tencent_WeKnora_internal_types.UserPreferences:
properties:
+ browser_search_instructions:
+ description: BrowserSearchInstructions customizes browser search for this
+ user. Nil/empty uses the platform default.
+ type: string
last_active_tenant_id:
description: |-
LastActiveTenantID remembers the last workspace the user actively
@@ -5944,6 +6009,11 @@ definitions:
internal_handler.UpdateAgentRequest:
properties:
avatar:
+ description: |-
+ Avatar travels as a pointer so an omitted field can be told apart from
+ an explicit clear: nil keeps the stored avatar, a pointer to "" wipes
+ it. As a plain string the two cases were indistinguishable, so a caller
+ that PUT only a config silently zeroed the avatar and still got a 200.
type: string
config:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.CustomAgentConfig'
@@ -6268,6 +6338,9 @@ definitions:
type: object
internal_handler.updateMyPreferencesRequest:
properties:
+ browser_search_instructions:
+ maxLength: 4000
+ type: string
last_active_tenant_id:
description: |-
LastActiveTenantID lets clients persist "after a fresh login,
@@ -6334,6 +6407,9 @@ definitions:
items:
type: string
type: array
+ local_browser_enabled:
+ description: Browser source
+ type: boolean
mcp_service_ids:
description: Per-request MCP services selected via @mention
items:
@@ -6378,6 +6454,21 @@ definitions:
description: Title for the session (optional)
type: string
type: object
+ internal_handler_session.ForkSessionRequest:
+ properties:
+ message_id:
+ description: |-
+ MessageID is the message to branch at. A user message copies history
+ strictly before it (the client prefills that question). An assistant
+ message copies history through that answer so the branch continues after it.
+ type: string
+ title:
+ description: Title is optional. Empty falls back to the source title plus
+ a suffix.
+ type: string
+ required:
+ - message_id
+ type: object
internal_handler_session.GenerateTitleRequest:
properties:
messages:
@@ -6456,6 +6547,30 @@ definitions:
required:
- query
type: object
+ internal_handler_session.SteerMessageRequest:
+ properties:
+ channel:
+ type: string
+ delivery:
+ description: Delivery is "after" (default) or "inject". See the constants
+ above.
+ type: string
+ expected_assistant_message_id:
+ description: |-
+ Optional for older clients. New clients pin delivery to the run they see
+ and supply a stable ID so a consume event may precede the HTTP response.
+ type: string
+ mentioned_items:
+ items:
+ $ref: '#/definitions/internal_handler_session.MentionedItemRequest'
+ type: array
+ query:
+ type: string
+ steer_id:
+ type: string
+ required:
+ - query
+ type: object
internal_handler_session.StopSessionRequest:
properties:
message_id:
@@ -6972,7 +7087,7 @@ paths:
post:
consumes:
- application/json
- description: Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程
+ description: Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,首次及后续启动均须通过桌面原生凭据认证,免除手动注册/登录流程
produces:
- application/json
responses:
@@ -9761,6 +9876,10 @@ paths:
description: Bad Request
schema:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "401":
+ description: Unauthorized
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
"403":
description: Forbidden
schema:
@@ -9769,10 +9888,6 @@ paths:
description: Not Found
schema:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
- "401":
- description: Unauthorized
- schema:
- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
"429":
description: Too Many Requests
schema:
@@ -11810,11 +11925,194 @@ paths:
summary: Get wiki statistics
tags:
- Wiki
+ /mcp-endpoints:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 端点列表
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 获取 MCP 端点列表
+ tags:
+ - MCP端点
+ post:
+ consumes:
+ - application/json
+ description: 为当前工作空间发布一个 MCP 端点,响应中的 token 只返回一次
+ parameters:
+ - description: 端点配置:name、description、enabled、knowledge_base_ids、tools 等
+ in: body
+ name: request
+ required: true
+ schema:
+ type: object
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: 创建的端点,含一次性 token
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: 请求参数错误
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 创建 MCP 端点
+ tags:
+ - MCP端点
+ /mcp-endpoints/{endpoint_id}:
+ delete:
+ parameters:
+ - description: 端点 ID
+ in: path
+ name: endpoint_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 删除成功
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: 端点不存在
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 删除 MCP 端点
+ tags:
+ - MCP端点
+ get:
+ parameters:
+ - description: 端点 ID
+ in: path
+ name: endpoint_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 端点详情
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: 端点不存在
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 获取 MCP 端点详情
+ tags:
+ - MCP端点
+ put:
+ consumes:
+ - application/json
+ parameters:
+ - description: 端点 ID
+ in: path
+ name: endpoint_id
+ required: true
+ type: string
+ - description: 要更新的字段,未提供的字段保持不变
+ in: body
+ name: request
+ required: true
+ schema:
+ type: object
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 更新后的端点
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: 请求参数错误
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: 端点不存在
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 更新 MCP 端点
+ tags:
+ - MCP端点
+ /mcp-endpoints/{endpoint_id}/rotate-token:
+ post:
+ description: 生成新令牌并立即作废旧令牌,响应中的 token 只返回一次
+ parameters:
+ - description: 端点 ID
+ in: path
+ name: endpoint_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 含新 token 的端点
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: 端点不存在
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 轮换 MCP 端点令牌
+ tags:
+ - MCP端点
+ /mcp-endpoints/tools:
+ get:
+ description: 返回工作空间 MCP 端点可勾选的工具清单、分组和默认勾选项
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 工具目录
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 获取 MCP 端点工具目录
+ tags:
+ - MCP端点
/mcp-services:
get:
consumes:
- application/json
- description: 获取当前空间的所有MCP服务
+ description: 获取当前空间的所有MCP服务(含已保存工具目录数量)
produces:
- application/json
responses:
@@ -12067,7 +12365,8 @@ paths:
post:
consumes:
- application/json
- description: 显式连接上游并原子替换完整目录。OAuth 服务写入当前用户的快照,Viewer 及以上可调用;静态认证写入租户共享快照,需要 Admin。
+ description: 显式连接上游并原子替换完整目录。OAuth 服务写入当前用户的快照,Viewer 及以上可调用;静态认证写入租户共享快照,需要
+ Admin。
parameters:
- description: MCP服务ID
in: path
@@ -13711,23 +14010,17 @@ paths:
- 组织管理
/organizations/{id}/search-tenants:
get:
- description: 按空间名搜索可邀请的空间(排除已加入的空间)用于邀请加入组织;按空间去重
parameters:
- description: 组织ID
in: path
name: id
required: true
type: string
- - description: 搜索关键词(空间名)
+ - description: Exact workspace ID
in: query
name: q
required: true
type: string
- - default: 10
- description: 返回数量限制
- in: query
- name: limit
- type: integer
produces:
- application/json
responses:
@@ -13736,13 +14029,9 @@ paths:
schema:
additionalProperties: true
type: object
- "403":
- description: Forbidden
- schema:
- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
security:
- Bearer: []
- summary: 搜索可邀请的空间
+ summary: Resolve a workspace ID for invitation
tags:
- 组织管理
/organizations/{id}/search-users:
@@ -14858,6 +15147,73 @@ paths:
summary: 取消置顶会话
tags:
- 会话
+ /sessions/{id}/steer:
+ get:
+ description: 刷新页面后用来恢复输入框上方的队列。没有正在运行的 turn 时返回空列表。
+ parameters:
+ - description: 会话 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "503":
+ description: 活 turn 查询失败,可重试
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 列出当前运行中尚未消费的排队消息
+ tags:
+ - 问答
+ /sessions/{id}/steer/{steer_id}:
+ delete:
+ description: 从当前运行的排队列表里去掉一条,不再注入也不再作为 follow-up 发出。
+ parameters:
+ - description: 会话 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ - description: 排队消息 ID
+ in: path
+ name: steer_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "503":
+ description: 活 turn 查询失败,可重试
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 删除一条排队中的消息
+ tags:
+ - 问答
/sessions/{session_id}/artifacts:
get:
description: 返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)
@@ -14884,6 +15240,49 @@ paths:
summary: 列出会话生成的产物文件
tags:
- 会话
+ /sessions/{session_id}/fork:
+ post:
+ consumes:
+ - application/json
+ description: 从指定的用户或助手消息处分叉出一个新会话。用户消息:复制其之前的历史并预填该问题;助手消息:复制含该回答在内的历史,从该轮沙箱状态继续。
+ parameters:
+ - description: 源会话 ID
+ in: path
+ name: session_id
+ required: true
+ type: string
+ - description: 分叉请求
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/internal_handler_session.ForkSessionRequest'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 新会话
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: 请求参数错误 / 分叉点角色不支持
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "404":
+ description: 会话或消息不存在
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "409":
+ description: 源会话正在生成中
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 分叉会话
+ tags:
+ - 会话
/sessions/{session_id}/messages/{message_id}/artifacts:
get:
responses: {}
@@ -14983,6 +15382,89 @@ paths:
summary: 置顶会话
tags:
- 会话
+ /sessions/{session_id}/steer:
+ post:
+ consumes:
+ - application/json
+ description: 向运行中的 agent turn 追加用户消息(after 排队 / inject 注入)。无活 turn 时返回 new_run。
+ parameters:
+ - description: 会话 ID
+ in: path
+ name: session_id
+ required: true
+ type: string
+ - description: 追加消息
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/internal_handler_session.SteerMessageRequest'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: queued | new_run
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: 请求参数错误
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "404":
+ description: 会话不存在
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "503":
+ description: 活 turn 查询失败,可重试
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 向运行中的对话追加消息
+ tags:
+ - 问答
+ /sessions/{session_id}/steer/{steer_id}/inject:
+ post:
+ description: 把一条 delivery=after 的排队消息改为 inject,运行中的 agent 会在下一轮边界读到它。
+ parameters:
+ - description: 会话 ID
+ in: path
+ name: session_id
+ required: true
+ type: string
+ - description: 排队消息 ID
+ in: path
+ name: steer_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: queued | new_run
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: Bad Request
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "503":
+ description: 活 turn 查询失败,可重试
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 将排队消息改为立即注入
+ tags:
+ - 问答
/sessions/{session_id}/stop:
post:
consumes:
diff --git a/frontend/src/api/mcp-endpoint.ts b/frontend/src/api/mcp-endpoint.ts
new file mode 100644
index 000000000..c00403b86
--- /dev/null
+++ b/frontend/src/api/mcp-endpoint.ts
@@ -0,0 +1,74 @@
+import { get, post, put, del } from '@/utils/request'
+
+export type McpEndpointToolGroup = 'retrieve' | 'chat' | 'wiki' | 'ingest'
+
+export interface McpEndpoint {
+ id: string
+ tenant_id: number
+ name: string
+ description: string
+ enabled: boolean
+ token_hint: string
+ knowledge_base_ids: string[]
+ tools: string[]
+ default_agent_id: string
+ rate_limit_per_minute: number
+ /** Public path the MCP client connects to, relative to the server origin. */
+ path: string
+ last_used_at?: string | null
+ created_at: string
+ updated_at: string
+ /** Only present on create / rotate responses; shown once. */
+ token?: string
+}
+
+export interface McpEndpointToolDefinition {
+ name: string
+ group: McpEndpointToolGroup
+ destructive: boolean
+}
+
+export interface McpEndpointToolCatalog {
+ groups: McpEndpointToolGroup[]
+ tools: McpEndpointToolDefinition[]
+ default_tools: string[]
+}
+
+export interface McpEndpointPayload {
+ name?: string
+ description?: string
+ enabled?: boolean
+ knowledge_base_ids?: string[]
+ tools?: string[]
+ default_agent_id?: string
+ rate_limit_per_minute?: number
+}
+
+interface Envelope<T> {
+ success: boolean
+ data: T
+}
+
+export function listMcpEndpoints() {
+ return get<Envelope<McpEndpoint[]>>('/api/v1/mcp-endpoints')
+}
+
+export function getMcpEndpointToolCatalog() {
+ return get<Envelope<McpEndpointToolCatalog>>('/api/v1/mcp-endpoints/tools')
+}
+
+export function createMcpEndpoint(data: McpEndpointPayload) {
+ return post<Envelope<McpEndpoint>>('/api/v1/mcp-endpoints', data)
+}
+
+export function updateMcpEndpoint(id: string, data: McpEndpointPayload) {
+ return put<Envelope<McpEndpoint>>(`/api/v1/mcp-endpoints/${id}`, data)
+}
+
+export function deleteMcpEndpoint(id: string) {
+ return del(`/api/v1/mcp-endpoints/${id}`)
+}
+
+export function rotateMcpEndpointToken(id: string) {
+ return post<Envelope<McpEndpoint>>(`/api/v1/mcp-endpoints/${id}/rotate-token`, {})
+}
diff --git a/frontend/src/config/deploymentCapabilities.ts b/frontend/src/config/deploymentCapabilities.ts
index e0b6f7bc7..ce7726f53 100644
--- a/frontend/src/config/deploymentCapabilities.ts
+++ b/frontend/src/config/deploymentCapabilities.ts
@@ -4,6 +4,7 @@ export const DEPLOYMENT_CAPABILITY_KEYS = [
'integrations.im',
'integrations.embed',
'integrations.api',
+ 'integrations.mcpserver',
'settings.mcp',
'settings.websearch',
'settings.vectorstore',
diff --git a/frontend/src/config/integrations.ts b/frontend/src/config/integrations.ts
index bed068b6c..29f4c4b4c 100644
--- a/frontend/src/config/integrations.ts
+++ b/frontend/src/config/integrations.ts
@@ -5,9 +5,9 @@ export const CHROME_EXTENSION_URL =
export const CLAWHUB_SKILL_URL = 'https://clawhub.ai/lyingbug/weknora'
-export type IntegrationTab = 'im' | 'embed' | 'api' | 'cli' | 'chrome' | 'claw'
+export type IntegrationTab = 'im' | 'embed' | 'api' | 'mcpserver' | 'cli' | 'chrome' | 'claw'
-export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'api', 'cli', 'chrome', 'claw']
+export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'api', 'mcpserver', 'cli', 'chrome', 'claw']
/** Aligns with Settings.vue SECTION_MIN_ROLE.api and router.go g.Owner() on /api-principal-config. */
export type IntegrationTabRole = 'viewer' | 'contributor' | 'admin' | 'owner'
@@ -20,6 +20,7 @@ export const INTEGRATION_TAB_CAPABILITY: Partial<Record<IntegrationTab, Deployme
im: 'integrations.im',
embed: 'integrations.embed',
api: 'integrations.api',
+ mcpserver: 'integrations.mcpserver',
}
export type IntegrationPreviewIcon =
@@ -34,6 +35,7 @@ export const INTEGRATION_PREVIEW_ITEMS: Array<{
{ key: 'im', icon: { type: 'icon', name: 'chat-message' } },
{ key: 'embed', icon: { type: 'icon', name: 'code' } },
{ key: 'api', icon: { type: 'icon', name: 'secured' } },
+ { key: 'mcpserver', icon: { type: 'icon', name: 'tools' } },
{ key: 'cli', icon: { type: 'icon', name: 'code' } },
{ key: 'chrome', icon: { type: 'icon', name: 'extension' } },
{ key: 'claw', icon: { type: 'emoji', value: '🦞' } },
diff --git a/frontend/src/config/settingsRoute.test.ts b/frontend/src/config/settingsRoute.test.ts
index 5439cf1f1..715db7fab 100644
--- a/frontend/src/config/settingsRoute.test.ts
+++ b/frontend/src/config/settingsRoute.test.ts
@@ -47,6 +47,9 @@ test('legacy api / integrations / bare-tab query strings normalize to nav keys',
assert.equal(normalizeSettingsSection('api'), 'integration-api')
assert.equal(normalizeSettingsSection('claw'), 'integration-claw')
assert.equal(normalizeSettingsSection('cli'), 'integration-cli')
+ assert.equal(normalizeSettingsSection('mcpserver'), 'integration-mcpserver')
+ // 'mcp' is the MCP-client settings page, not the MCP server integration tab.
+ assert.equal(normalizeSettingsSection('mcp'), 'mcp')
assert.equal(normalizeSettingsSection('integrations', 'cli'), 'integration-cli')
assert.equal(normalizeSettingsSection('integrations', 'embed'), 'integration-embed')
assert.equal(normalizeSettingsSection('integrations'), 'integration-im')
diff --git a/frontend/src/i18n/localeKeyAudit.ts b/frontend/src/i18n/localeKeyAudit.ts
index c8831f8b7..952afdae4 100644
--- a/frontend/src/i18n/localeKeyAudit.ts
+++ b/frontend/src/i18n/localeKeyAudit.ts
@@ -92,6 +92,8 @@ const EXTRA_PREFIXES = [
'kbSettings.parser.engines.',
'model.editor.description.',
'integrations.tabs.',
+ 'integrations.mcpserver.tools.',
+ 'integrations.mcpserver.groups.',
'knowledgeStages.stage.',
'knowledgeStages.status.',
'system.globalSettings.runtime.pools.',
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 0ab377696..60dc07c77 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -6651,13 +6651,116 @@ export default {
copied: 'Copied',
},
title: 'Publish & Integrations',
+ mcpserver: {
+ title: 'MCP Server',
+ subtitle: 'Publish this workspace as an MCP server that Claude Desktop, Cursor, Claude Code and other MCP clients connect to directly. Each endpoint has its own token, knowledge-base scope and tool list.',
+ listTitle: 'Published endpoints',
+ empty: 'No MCP endpoints yet',
+ disabled: 'Disabled',
+ cardSummary: '{tools} tools · {scope}',
+ scopeAll: 'All knowledge bases',
+ scopeCount: '{count} knowledge bases',
+ create: 'New endpoint',
+ editTitle: 'Edit MCP endpoint',
+ createTitle: 'New MCP endpoint',
+ drawerDesc: 'The endpoint decides which knowledge bases a client can see and which tools it can call. The token is shown once, on creation and rotation.',
+ sectionBasic: 'Basics',
+ nameLabel: 'Name',
+ namePlaceholder: 'e.g. Product docs assistant',
+ descriptionLabel: 'Description',
+ descriptionPlaceholder: 'Optional: who uses this endpoint and for what',
+ enabledLabel: 'Enabled',
+ sectionScope: 'Knowledge-base scope',
+ kbScopeLabel: 'Accessible knowledge bases',
+ kbScopePlaceholder: 'Leave empty for every knowledge base in the workspace',
+ kbScopeHint: 'Every retrieval, ask and write tool is confined to these knowledge bases. Empty means the whole workspace.',
+ sectionTools: 'Exposed tools',
+ toolsHint: 'Only checked tools appear in the client tool list; unchecked tools are refused even when called by name. Write tools are off by default.',
+ clearGroup: 'Clear',
+ selectGroup: 'Select all',
+ toolsRequired: 'Select at least one tool',
+ groups: {
+ retrieve: 'Retrieval & reading',
+ chat: 'Question answering',
+ wiki: 'Wiki',
+ ingest: 'Writes (enable with care)',
+ },
+ tools: {
+ list_knowledge_bases: 'List knowledge bases',
+ list_knowledge_basesDesc: 'Return the knowledge bases in scope and the retrieval modes each supports',
+ search_knowledge: 'Semantic search',
+ search_knowledgeDesc: 'Find relevant passages for a natural-language question, with sources',
+ grep_chunks: 'Keyword / regex search',
+ grep_chunksDesc: 'Case-insensitive regex over raw chunks; best for exact terms, codes and names',
+ list_documents: 'List documents',
+ list_documentsDesc: 'Page through the documents of one knowledge base',
+ read_document: 'Read document',
+ read_documentDesc: 'Read a document\'s metadata and its chunks in order',
+ ask: 'Ask',
+ askDesc: 'Run the agent configured on this endpoint and return a cited answer; supports follow-up turns',
+ wiki_search: 'Search wiki',
+ wiki_searchDesc: 'Search the generated wiki pages',
+ wiki_read_page: 'Read wiki page',
+ wiki_read_pageDesc: 'Read one wiki page by slug',
+ wiki_index: 'Browse wiki index',
+ wiki_indexDesc: 'Show the table of contents of a knowledge base wiki',
+ add_document: 'Add document',
+ add_documentDesc: 'Add a document from Markdown text or a URL',
+ update_document: 'Update document',
+ update_documentDesc: 'Replace the content or title of a Markdown document',
+ delete_document: 'Delete document',
+ delete_documentDesc: 'Permanently delete a document and its index data',
+ },
+ sectionAsk: 'Ask settings',
+ defaultAgentLabel: 'Default agent',
+ defaultAgentPlaceholder: 'Built-in quick answer when empty',
+ defaultAgentHint: 'The agent the ask tool runs. Clients cannot choose an agent themselves; empty means the built-in quick answer.',
+ sectionLimits: 'Rate limit',
+ rateLimitLabel: 'Max calls per minute',
+ rateLimitHint: 'Applies to all tool calls on this endpoint; clients get a rate-limit error above it.',
+ sectionConnect: 'Connection',
+ connectHintExisting: 'The token was shown once at creation (current token starts with {hint}…). Rotate the token to get a new one.',
+ showSnippets: 'Show client configuration',
+ tokenDialogTitle: 'Endpoint ready, save the token',
+ connectDialogTitle: 'Connect to this endpoint',
+ tokenOnce: 'This token is shown only once. Copy it now and store it somewhere safe.',
+ connectPlaceholderHint: 'For security the token is not shown again; the examples below use a placeholder you must replace with the token you saved.',
+ tokenLabel: 'Token',
+ urlLabel: 'Endpoint URL',
+ snippet: {
+ httpTitle: 'Cursor / VS Code / Claude Desktop',
+ httpDesc: 'Clients that speak Streamable HTTP take this mcpServers block as is.',
+ claudeCodeTitle: 'Claude Code',
+ claudeCodeDesc: 'One command in the terminal.',
+ stdioTitle: 'stdio-only clients',
+ stdioDesc: 'Bridged through mcp-remote; requires Node.js on the client machine.',
+ },
+ loadFailed: 'Failed to load MCP endpoints',
+ nameRequired: 'Name is required',
+ updated: 'Endpoint updated',
+ created: 'Endpoint created',
+ saveFailed: 'Save failed',
+ deleted: 'Endpoint deleted',
+ deleteFailed: 'Delete failed',
+ rotated: 'Token rotated; the old token stopped working',
+ rotateFailed: 'Failed to rotate token',
+ disabledToast: 'Endpoint disabled',
+ enabledToast: 'Endpoint enabled',
+ menuConnect: 'Connection info',
+ menuDisable: 'Disable',
+ menuEnable: 'Enable',
+ menuRotate: 'Rotate token',
+ copied: 'Copied',
+ deleteConfirm: 'Clients using this endpoint disconnect immediately. Delete it?',
+ },
tabs: {
im: 'IM Integration',
embed: 'Web Embed',
api: 'API Integration',
chrome: 'Chrome Extension',
cli: 'CLI',
- claw: 'Claw Skill'
+ claw: 'Claw Skill',
+ mcpserver: 'MCP Server'
},
api: {
title: 'API Integration',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 646e42506..21a8c69a0 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -6651,13 +6651,116 @@ export default {
copied: 'コピーしました',
},
title: '公開と連携',
+ mcpserver: {
+ title: 'MCP サーバー',
+ subtitle: 'このワークスペースを MCP サーバーとして公開し、Claude Desktop、Cursor、Claude Code などの MCP クライアントから直接接続できます。エンドポイントごとにトークン、ナレッジベース範囲、ツール一覧を設定します。',
+ listTitle: '公開中のエンドポイント',
+ empty: 'MCP エンドポイントはまだありません',
+ disabled: '停止中',
+ cardSummary: '{tools} 個のツール · {scope}',
+ scopeAll: 'すべてのナレッジベース',
+ scopeCount: '{count} 個のナレッジベース',
+ create: 'エンドポイントを作成',
+ editTitle: 'MCP エンドポイントを編集',
+ createTitle: 'MCP エンドポイントを作成',
+ drawerDesc: 'エンドポイントは、クライアントが参照できるナレッジベースと呼び出せるツールを決めます。トークンは作成時とローテーション時に一度だけ表示されます。',
+ sectionBasic: '基本情報',
+ nameLabel: '名前',
+ namePlaceholder: '例:製品ドキュメントアシスタント',
+ descriptionLabel: '説明',
+ descriptionPlaceholder: '任意:用途や利用者',
+ enabledLabel: '有効',
+ sectionScope: 'ナレッジベース範囲',
+ kbScopeLabel: 'アクセスできるナレッジベース',
+ kbScopePlaceholder: '空欄でワークスペース内のすべて',
+ kbScopeHint: '検索・質問応答・書き込みのすべてのツールはこの範囲に限定されます。空欄の場合はワークスペース全体です。',
+ sectionTools: '公開するツール',
+ toolsHint: 'チェックしたツールだけがクライアントのツール一覧に表示され、未チェックのツールは名前指定でも拒否されます。書き込み系はデフォルトで無効です。',
+ clearGroup: '解除',
+ selectGroup: 'すべて選択',
+ toolsRequired: '少なくとも 1 つのツールを選択してください',
+ groups: {
+ retrieve: '検索と閲覧',
+ chat: '質問応答',
+ wiki: 'Wiki',
+ ingest: '書き込み(慎重に有効化)',
+ },
+ tools: {
+ list_knowledge_bases: 'ナレッジベース一覧',
+ list_knowledge_basesDesc: '範囲内のナレッジベースと対応する検索方式を返します',
+ search_knowledge: 'セマンティック検索',
+ search_knowledgeDesc: '自然言語の質問に関連する箇所を出典付きで検索します',
+ grep_chunks: 'キーワード / 正規表現検索',
+ grep_chunksDesc: 'チャンク本文に対する大文字小文字を区別しない正規表現検索。固有名詞やコードに最適',
+ list_documents: 'ドキュメント一覧',
+ list_documentsDesc: 'ナレッジベース内のドキュメントをページ単位で一覧します',
+ read_document: 'ドキュメントを読む',
+ read_documentDesc: 'ドキュメントのメタ情報とチャンクを順に読みます',
+ ask: '質問する',
+ askDesc: 'エンドポイントに設定されたエージェントを実行し、引用付きの回答を返します。続きの質問にも対応',
+ wiki_search: 'Wiki を検索',
+ wiki_searchDesc: '生成された Wiki ページを検索します',
+ wiki_read_page: 'Wiki ページを読む',
+ wiki_read_pageDesc: 'slug を指定して Wiki ページを読みます',
+ wiki_index: 'Wiki 目次',
+ wiki_indexDesc: 'ナレッジベースの Wiki の目次を表示します',
+ add_document: 'ドキュメント追加',
+ add_documentDesc: 'Markdown テキストまたは URL からドキュメントを追加します',
+ update_document: 'ドキュメント更新',
+ update_documentDesc: 'Markdown ドキュメントの内容やタイトルを置き換えます',
+ delete_document: 'ドキュメント削除',
+ delete_documentDesc: 'ドキュメントとインデックスを完全に削除します',
+ },
+ sectionAsk: '質問応答の設定',
+ defaultAgentLabel: '既定のエージェント',
+ defaultAgentPlaceholder: '未選択時は内蔵のクイック回答',
+ defaultAgentHint: 'ask ツールが実行するエージェントです。クライアント側でエージェントを選ぶことはできません。未設定時は内蔵のクイック回答を使用します。',
+ sectionLimits: 'レート制限',
+ rateLimitLabel: '1 分あたりの最大呼び出し数',
+ rateLimitHint: 'このエンドポイントのすべてのツール呼び出しに適用されます。',
+ sectionConnect: '接続情報',
+ connectHintExisting: 'トークンは作成時に一度だけ表示されました(現在のトークンは {hint}… で始まります)。再取得するにはローテーションしてください。',
+ showSnippets: 'クライアント設定例を表示',
+ tokenDialogTitle: 'エンドポイントの準備完了。トークンを保存してください',
+ connectDialogTitle: 'このエンドポイントに接続',
+ tokenOnce: 'このトークンは一度しか表示されません。今すぐコピーして安全に保管してください。',
+ connectPlaceholderHint: 'セキュリティのためトークンは再表示されません。以下の例のプレースホルダーを保存したトークンに置き換えてください。',
+ tokenLabel: 'トークン',
+ urlLabel: 'エンドポイント URL',
+ snippet: {
+ httpTitle: 'Cursor / VS Code / Claude Desktop',
+ httpDesc: 'Streamable HTTP 対応クライアントはこの mcpServers 設定をそのまま使えます。',
+ claudeCodeTitle: 'Claude Code',
+ claudeCodeDesc: 'ターミナルで 1 コマンド実行するだけです。',
+ stdioTitle: 'stdio のみ対応のクライアント',
+ stdioDesc: 'mcp-remote 経由で接続します。クライアント側に Node.js が必要です。',
+ },
+ loadFailed: 'MCP エンドポイントの読み込みに失敗しました',
+ nameRequired: '名前を入力してください',
+ updated: 'エンドポイントを更新しました',
+ created: 'エンドポイントを作成しました',
+ saveFailed: '保存に失敗しました',
+ deleted: 'エンドポイントを削除しました',
+ deleteFailed: '削除に失敗しました',
+ rotated: 'トークンをローテーションしました。旧トークンは無効です',
+ rotateFailed: 'トークンのローテーションに失敗しました',
+ disabledToast: 'エンドポイントを停止しました',
+ enabledToast: 'エンドポイントを有効にしました',
+ menuConnect: '接続情報',
+ menuDisable: '停止',
+ menuEnable: '有効化',
+ menuRotate: 'トークンをローテーション',
+ copied: 'コピーしました',
+ deleteConfirm: 'このエンドポイントを使用中のクライアントは直ちに切断されます。削除しますか?',
+ },
tabs: {
im: 'IM連携',
embed: 'Web埋め込み',
api: 'API連携',
chrome: 'Chrome拡張機能',
cli: 'CLI',
- claw: 'Clawスキル'
+ claw: 'Clawスキル',
+ mcpserver: 'MCP サーバー'
},
api: {
title: 'API連携',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 975fb5a8e..69f163f2e 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -679,13 +679,116 @@ export default {
saveSuccess: 'API 통합 설정이 저장되었습니다',
autoSaveNeedSecret: '서명 토큰 모드는 자동 저장 전에 HMAC secret이 필요합니다.'
},
+ mcpserver: {
+ title: 'MCP 서버',
+ subtitle: '이 워크스페이스를 MCP 서버로 게시하여 Claude Desktop, Cursor, Claude Code 등 MCP 클라이언트가 직접 연결하게 합니다. 엔드포인트마다 별도의 토큰, 지식 베이스 범위, 도구 목록을 가집니다.',
+ listTitle: '게시된 엔드포인트',
+ empty: '아직 MCP 엔드포인트가 없습니다',
+ disabled: '비활성',
+ cardSummary: '도구 {tools}개 · {scope}',
+ scopeAll: '모든 지식 베이스',
+ scopeCount: '지식 베이스 {count}개',
+ create: '새 엔드포인트',
+ editTitle: 'MCP 엔드포인트 편집',
+ createTitle: '새 MCP 엔드포인트',
+ drawerDesc: '엔드포인트는 클라이언트가 볼 수 있는 지식 베이스와 호출할 수 있는 도구를 결정합니다. 토큰은 생성 및 교체 시 한 번만 표시됩니다.',
+ sectionBasic: '기본 정보',
+ nameLabel: '이름',
+ namePlaceholder: '예: 제품 문서 도우미',
+ descriptionLabel: '설명',
+ descriptionPlaceholder: '선택: 누가 어떤 용도로 사용하는지',
+ enabledLabel: '활성화',
+ sectionScope: '지식 베이스 범위',
+ kbScopeLabel: '접근 가능한 지식 베이스',
+ kbScopePlaceholder: '비워 두면 워크스페이스의 모든 지식 베이스',
+ kbScopeHint: '검색, 질문, 쓰기 도구 모두 이 범위 안에서만 동작합니다. 비워 두면 워크스페이스 전체입니다.',
+ sectionTools: '노출할 도구',
+ toolsHint: '선택한 도구만 클라이언트 도구 목록에 나타나며, 선택하지 않은 도구는 이름으로 호출해도 거부됩니다. 쓰기 도구는 기본적으로 꺼져 있습니다.',
+ clearGroup: '해제',
+ selectGroup: '모두 선택',
+ toolsRequired: '도구를 하나 이상 선택하세요',
+ groups: {
+ retrieve: '검색 및 읽기',
+ chat: '질의응답',
+ wiki: 'Wiki',
+ ingest: '쓰기 (신중하게 활성화)',
+ },
+ tools: {
+ list_knowledge_bases: '지식 베이스 목록',
+ list_knowledge_basesDesc: '범위 내 지식 베이스와 지원하는 검색 방식을 반환합니다',
+ search_knowledge: '의미 검색',
+ search_knowledgeDesc: '자연어 질문과 관련된 구절을 출처와 함께 찾습니다',
+ grep_chunks: '키워드 / 정규식 검색',
+ grep_chunksDesc: '원본 청크에 대한 대소문자 구분 없는 정규식 검색. 정확한 용어, 코드, 이름에 적합',
+ list_documents: '문서 목록',
+ list_documentsDesc: '지식 베이스의 문서를 페이지 단위로 나열합니다',
+ read_document: '문서 읽기',
+ read_documentDesc: '문서의 메타데이터와 청크를 순서대로 읽습니다',
+ ask: '질문하기',
+ askDesc: '엔드포인트에 설정된 에이전트를 실행하여 인용이 포함된 답변을 반환합니다. 후속 질문 지원',
+ wiki_search: 'Wiki 검색',
+ wiki_searchDesc: '생성된 Wiki 페이지를 검색합니다',
+ wiki_read_page: 'Wiki 페이지 읽기',
+ wiki_read_pageDesc: 'slug로 Wiki 페이지 하나를 읽습니다',
+ wiki_index: 'Wiki 목차',
+ wiki_indexDesc: '지식 베이스 Wiki의 목차를 표시합니다',
+ add_document: '문서 추가',
+ add_documentDesc: 'Markdown 텍스트 또는 URL로 문서를 추가합니다',
+ update_document: '문서 업데이트',
+ update_documentDesc: 'Markdown 문서의 내용 또는 제목을 교체합니다',
+ delete_document: '문서 삭제',
+ delete_documentDesc: '문서와 인덱스 데이터를 영구 삭제합니다',
+ },
+ sectionAsk: '질문 설정',
+ defaultAgentLabel: '기본 에이전트',
+ defaultAgentPlaceholder: '비어 있으면 내장 빠른 답변 사용',
+ defaultAgentHint: 'ask 도구가 실행하는 에이전트입니다. 클라이언트는 에이전트를 직접 선택할 수 없습니다. 비어 있으면 내장 빠른 답변을 사용합니다.',
+ sectionLimits: '속도 제한',
+ rateLimitLabel: '분당 최대 호출 수',
+ rateLimitHint: '이 엔드포인트의 모든 도구 호출에 적용되며, 초과 시 클라이언트는 제한 오류를 받습니다.',
+ sectionConnect: '연결 정보',
+ connectHintExisting: '토큰은 생성 시 한 번만 표시되었습니다(현재 토큰은 {hint}…로 시작). 새 토큰이 필요하면 교체하세요.',
+ showSnippets: '클라이언트 설정 예시 보기',
+ tokenDialogTitle: '엔드포인트 준비 완료, 토큰을 저장하세요',
+ connectDialogTitle: '이 엔드포인트에 연결',
+ tokenOnce: '이 토큰은 한 번만 표시됩니다. 지금 복사하여 안전하게 보관하세요.',
+ connectPlaceholderHint: '보안을 위해 토큰은 다시 표시되지 않습니다. 아래 예시의 자리 표시자를 저장한 토큰으로 바꾸세요.',
+ tokenLabel: '토큰',
+ urlLabel: '엔드포인트 URL',
+ snippet: {
+ httpTitle: 'Cursor / VS Code / Claude Desktop',
+ httpDesc: 'Streamable HTTP를 지원하는 클라이언트는 이 mcpServers 블록을 그대로 사용합니다.',
+ claudeCodeTitle: 'Claude Code',
+ claudeCodeDesc: '터미널에서 명령 한 줄이면 됩니다.',
+ stdioTitle: 'stdio 전용 클라이언트',
+ stdioDesc: 'mcp-remote로 연결하며 클라이언트에 Node.js가 필요합니다.',
+ },
+ loadFailed: 'MCP 엔드포인트를 불러오지 못했습니다',
+ nameRequired: '이름을 입력하세요',
+ updated: '엔드포인트가 업데이트되었습니다',
+ created: '엔드포인트가 생성되었습니다',
+ saveFailed: '저장 실패',
+ deleted: '엔드포인트가 삭제되었습니다',
+ deleteFailed: '삭제 실패',
+ rotated: '토큰이 교체되었습니다. 이전 토큰은 즉시 무효화됩니다',
+ rotateFailed: '토큰 교체 실패',
+ disabledToast: '엔드포인트가 비활성화되었습니다',
+ enabledToast: '엔드포인트가 활성화되었습니다',
+ menuConnect: '연결 정보',
+ menuDisable: '비활성화',
+ menuEnable: '활성화',
+ menuRotate: '토큰 교체',
+ copied: '복사됨',
+ deleteConfirm: '이 엔드포인트를 사용하는 클라이언트가 즉시 끊깁니다. 삭제할까요?',
+ },
tabs: {
im: 'IM 통합',
embed: '웹 임베드',
api: 'API 연동',
chrome: 'Chrome 확장',
cli: 'CLI',
- claw: 'Claw Skill'
+ claw: 'Claw Skill',
+ mcpserver: 'MCP 서버'
}
},
datasource: {
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index b8cd9ab12..6de9098c9 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -679,13 +679,116 @@ export default {
saveSuccess: 'Настройки API-интеграции сохранены',
autoSaveNeedSecret: 'Для signed-token режима нужен HMAC secret перед автосохранением.'
},
+ mcpserver: {
+ title: 'MCP-сервер',
+ subtitle: 'Опубликуйте это рабочее пространство как MCP-сервер, к которому напрямую подключаются Claude Desktop, Cursor, Claude Code и другие MCP-клиенты. У каждой конечной точки свой токен, область баз знаний и список инструментов.',
+ listTitle: 'Опубликованные конечные точки',
+ empty: 'Конечных точек MCP пока нет',
+ disabled: 'Отключена',
+ cardSummary: 'Инструментов: {tools} · {scope}',
+ scopeAll: 'Все базы знаний',
+ scopeCount: 'Баз знаний: {count}',
+ create: 'Новая конечная точка',
+ editTitle: 'Изменить конечную точку MCP',
+ createTitle: 'Новая конечная точка MCP',
+ drawerDesc: 'Конечная точка определяет, какие базы знаний видит клиент и какие инструменты может вызывать. Токен показывается один раз: при создании и при ротации.',
+ sectionBasic: 'Основное',
+ nameLabel: 'Название',
+ namePlaceholder: 'Например: помощник по документации',
+ descriptionLabel: 'Описание',
+ descriptionPlaceholder: 'Необязательно: кто и для чего использует',
+ enabledLabel: 'Включена',
+ sectionScope: 'Область баз знаний',
+ kbScopeLabel: 'Доступные базы знаний',
+ kbScopePlaceholder: 'Пусто — все базы знаний пространства',
+ kbScopeHint: 'Все инструменты поиска, вопросов и записи ограничены этими базами знаний. Пусто означает всё пространство.',
+ sectionTools: 'Доступные инструменты',
+ toolsHint: 'В список клиента попадают только отмеченные инструменты; неотмеченные отклоняются даже при вызове по имени. Инструменты записи по умолчанию выключены.',
+ clearGroup: 'Снять',
+ selectGroup: 'Выбрать все',
+ toolsRequired: 'Выберите хотя бы один инструмент',
+ groups: {
+ retrieve: 'Поиск и чтение',
+ chat: 'Вопросы и ответы',
+ wiki: 'Wiki',
+ ingest: 'Запись (включайте осторожно)',
+ },
+ tools: {
+ list_knowledge_bases: 'Список баз знаний',
+ list_knowledge_basesDesc: 'Возвращает базы знаний в области и поддерживаемые режимы поиска',
+ search_knowledge: 'Семантический поиск',
+ search_knowledgeDesc: 'Находит релевантные фрагменты по вопросу на естественном языке, с источниками',
+ grep_chunks: 'Поиск по ключевым словам / regex',
+ grep_chunksDesc: 'Регистронезависимый regex по исходным фрагментам; подходит для точных терминов, кодов и имён',
+ list_documents: 'Список документов',
+ list_documentsDesc: 'Постраничный список документов одной базы знаний',
+ read_document: 'Прочитать документ',
+ read_documentDesc: 'Метаданные документа и его фрагменты по порядку',
+ ask: 'Задать вопрос',
+ askDesc: 'Запускает агента, настроенного на конечной точке, и возвращает ответ с цитатами; поддерживает продолжение диалога',
+ wiki_search: 'Поиск по Wiki',
+ wiki_searchDesc: 'Поиск по сгенерированным страницам Wiki',
+ wiki_read_page: 'Прочитать страницу Wiki',
+ wiki_read_pageDesc: 'Читает одну страницу Wiki по slug',
+ wiki_index: 'Оглавление Wiki',
+ wiki_indexDesc: 'Показывает оглавление Wiki базы знаний',
+ add_document: 'Добавить документ',
+ add_documentDesc: 'Добавляет документ из Markdown-текста или по URL',
+ update_document: 'Обновить документ',
+ update_documentDesc: 'Заменяет содержимое или заголовок Markdown-документа',
+ delete_document: 'Удалить документ',
+ delete_documentDesc: 'Безвозвратно удаляет документ и его индекс',
+ },
+ sectionAsk: 'Настройки вопросов',
+ defaultAgentLabel: 'Агент по умолчанию',
+ defaultAgentPlaceholder: 'Пусто — встроенный быстрый ответ',
+ defaultAgentHint: 'Агент, которого запускает инструмент ask. Клиент не может выбрать агента сам; пусто — встроенный быстрый ответ.',
+ sectionLimits: 'Ограничение частоты',
+ rateLimitLabel: 'Максимум вызовов в минуту',
+ rateLimitHint: 'Применяется ко всем вызовам инструментов этой конечной точки; при превышении клиент получает ошибку.',
+ sectionConnect: 'Подключение',
+ connectHintExisting: 'Токен показывался один раз при создании (текущий начинается с {hint}…). Чтобы получить новый, выполните ротацию.',
+ showSnippets: 'Показать примеры конфигурации клиента',
+ tokenDialogTitle: 'Конечная точка готова, сохраните токен',
+ connectDialogTitle: 'Подключение к конечной точке',
+ tokenOnce: 'Токен показывается только один раз. Скопируйте его сейчас и сохраните в надёжном месте.',
+ connectPlaceholderHint: 'Из соображений безопасности токен больше не показывается; в примерах ниже стоит заполнитель, замените его сохранённым токеном.',
+ tokenLabel: 'Токен',
+ urlLabel: 'URL конечной точки',
+ snippet: {
+ httpTitle: 'Cursor / VS Code / Claude Desktop',
+ httpDesc: 'Клиенты с поддержкой Streamable HTTP принимают этот блок mcpServers как есть.',
+ claudeCodeTitle: 'Claude Code',
+ claudeCodeDesc: 'Одна команда в терминале.',
+ stdioTitle: 'Клиенты только со stdio',
+ stdioDesc: 'Через мост mcp-remote; на машине клиента нужен Node.js.',
+ },
+ loadFailed: 'Не удалось загрузить конечные точки MCP',
+ nameRequired: 'Укажите название',
+ updated: 'Конечная точка обновлена',
+ created: 'Конечная точка создана',
+ saveFailed: 'Не удалось сохранить',
+ deleted: 'Конечная точка удалена',
+ deleteFailed: 'Не удалось удалить',
+ rotated: 'Токен заменён; старый токен больше не действует',
+ rotateFailed: 'Не удалось заменить токен',
+ disabledToast: 'Конечная точка отключена',
+ enabledToast: 'Конечная точка включена',
+ menuConnect: 'Подключение',
+ menuDisable: 'Отключить',
+ menuEnable: 'Включить',
+ menuRotate: 'Заменить токен',
+ copied: 'Скопировано',
+ deleteConfirm: 'Клиенты, использующие эту конечную точку, будут немедленно отключены. Удалить?',
+ },
tabs: {
im: 'IM-интеграция',
embed: 'Веб-встраивание',
api: 'API-интеграция',
chrome: 'Расширение Chrome',
cli: 'CLI',
- claw: 'Claw Skill'
+ claw: 'Claw Skill',
+ mcpserver: 'MCP-сервер'
}
},
datasource: {
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 8b6cb00ab..767a18025 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -679,13 +679,116 @@ export default {
saveSuccess: 'API 集成设置已保存',
autoSaveNeedSecret: '签名 Token 模式需要填写 HMAC 密钥后才能自动保存。'
},
+ mcpserver: {
+ title: 'MCP Server',
+ subtitle: '把当前空间发布为 MCP 服务,供 Claude Desktop、Cursor、Claude Code 等 MCP 客户端直接连接。每个端点有独立的令牌、知识库范围和工具清单。',
+ listTitle: '已发布的端点',
+ empty: '暂无 MCP 端点',
+ disabled: '已停用',
+ cardSummary: '{tools} 个工具 · {scope}',
+ scopeAll: '全部知识库',
+ scopeCount: '{count} 个知识库',
+ create: '新建端点',
+ editTitle: '编辑 MCP 端点',
+ createTitle: '新建 MCP 端点',
+ drawerDesc: '端点决定外部客户端能看到哪些知识库、能调用哪些工具。令牌只在创建和轮换时展示一次。',
+ sectionBasic: '基本信息',
+ nameLabel: '名称',
+ namePlaceholder: '例如:产品文档助手',
+ descriptionLabel: '说明',
+ descriptionPlaceholder: '可选,说明这个端点给谁用、用于什么场景',
+ enabledLabel: '启用端点',
+ sectionScope: '知识库范围',
+ kbScopeLabel: '可访问的知识库',
+ kbScopePlaceholder: '留空表示空间内全部知识库',
+ kbScopeHint: '所有检索、问答和写入工具都只在这些知识库内生效。留空时端点可访问空间内的全部知识库。',
+ sectionTools: '暴露的工具',
+ toolsHint: '只有勾选的工具会出现在客户端的工具列表中,未勾选的工具即使按名字调用也会被拒绝。写入类工具默认关闭。',
+ clearGroup: '取消全选',
+ selectGroup: '全选',
+ toolsRequired: '至少勾选一个工具',
+ groups: {
+ retrieve: '检索与阅读',
+ chat: '问答',
+ wiki: 'Wiki',
+ ingest: '写入(谨慎开启)',
+ },
+ tools: {
+ list_knowledge_bases: '列出知识库',
+ list_knowledge_basesDesc: '返回端点范围内的知识库及其支持的检索方式',
+ search_knowledge: '语义搜索',
+ search_knowledgeDesc: '按自然语言问题在知识库中检索相关片段并附来源',
+ grep_chunks: '关键词/正则搜索',
+ grep_chunksDesc: '对原始分块做大小写不敏感的正则匹配,适合精确词、编号、代码',
+ list_documents: '列出文档',
+ list_documentsDesc: '分页列出某个知识库下的文档',
+ read_document: '阅读文档',
+ read_documentDesc: '按顺序读取文档的元信息和分块内容',
+ ask: '问答',
+ askDesc: '运行端点配置的默认 Agent,返回带引用的完整回答,支持多轮续聊',
+ wiki_search: '搜索 Wiki',
+ wiki_searchDesc: '在知识库生成的 Wiki 页面中搜索',
+ wiki_read_page: '读取 Wiki 页面',
+ wiki_read_pageDesc: '按 slug 读取一篇 Wiki 页面',
+ wiki_index: '浏览 Wiki 目录',
+ wiki_indexDesc: '查看某个知识库 Wiki 的目录结构',
+ add_document: '新增文档',
+ add_documentDesc: '用 Markdown 文本或 URL 向知识库添加文档',
+ update_document: '更新文档',
+ update_documentDesc: '替换 Markdown 文档的内容或标题',
+ delete_document: '删除文档',
+ delete_documentDesc: '永久删除文档及其索引数据',
+ },
+ sectionAsk: '问答设置',
+ defaultAgentLabel: '默认 Agent',
+ defaultAgentPlaceholder: '未选择时使用内置快速问答',
+ defaultAgentHint: '调用 ask 工具时使用的 Agent;客户端无法自行指定 Agent。留空时使用内置快速问答。',
+ sectionLimits: '限流',
+ rateLimitLabel: '每分钟最多调用次数',
+ rateLimitHint: '对该端点所有工具调用的总限制,超出后客户端会收到限流提示。',
+ sectionConnect: '连接信息',
+ connectHintExisting: '令牌只在创建时展示(当前令牌前缀 {hint}…)。如需重新获取,请轮换令牌。',
+ showSnippets: '查看客户端配置示例',
+ tokenDialogTitle: '端点已就绪,请保存令牌',
+ connectDialogTitle: '连接此端点',
+ tokenOnce: '令牌只展示这一次,关闭后无法再次查看。请立即复制并妥善保存。',
+ connectPlaceholderHint: '出于安全考虑不会再次展示令牌,下面的示例用占位符代替,请替换为你保存的令牌。',
+ tokenLabel: '令牌',
+ urlLabel: '端点地址',
+ snippet: {
+ httpTitle: 'Cursor / VS Code / Claude Desktop',
+ httpDesc: '支持 Streamable HTTP 的客户端直接写入 mcpServers 配置。',
+ claudeCodeTitle: 'Claude Code',
+ claudeCodeDesc: '在终端执行一条命令即可添加。',
+ stdioTitle: '仅支持 stdio 的客户端',
+ stdioDesc: '通过 mcp-remote 桥接,需要本地安装 Node.js。',
+ },
+ loadFailed: '加载 MCP 端点失败',
+ nameRequired: '请填写名称',
+ updated: '端点已更新',
+ created: '端点已创建',
+ saveFailed: '保存失败',
+ deleted: '端点已删除',
+ deleteFailed: '删除失败',
+ rotated: '令牌已轮换,旧令牌立即失效',
+ rotateFailed: '轮换令牌失败',
+ disabledToast: '端点已停用',
+ enabledToast: '端点已启用',
+ menuConnect: '连接信息',
+ menuDisable: '停用',
+ menuEnable: '启用',
+ menuRotate: '轮换令牌',
+ copied: '已复制',
+ deleteConfirm: '删除后使用该端点的客户端会立即断开,确定删除?',
+ },
tabs: {
im: 'IM 集成',
embed: '网页嵌入',
api: 'API 集成',
chrome: 'Chrome 插件',
cli: 'CLI',
- claw: 'Claw Skill'
+ claw: 'Claw Skill',
+ mcpserver: 'MCP Server'
}
},
datasource: {
diff --git a/frontend/src/views/integrations/IntegrationSettingsSection.vue b/frontend/src/views/integrations/IntegrationSettingsSection.vue
index 629a604e5..d7f9e2e2f 100644
--- a/frontend/src/views/integrations/IntegrationSettingsSection.vue
+++ b/frontend/src/views/integrations/IntegrationSettingsSection.vue
@@ -36,6 +36,14 @@
<ApiIntegrationSettings />
</div>
+ <div v-if="tab === 'mcpserver'" class="section">
+ <div class="section-header">
+ <h2>{{ $t('integrations.mcpserver.title') }}</h2>
+ <p class="section-description">{{ $t('integrations.mcpserver.subtitle') }}</p>
+ </div>
+ <McpServerIntegrationSettings />
+ </div>
+
<ChromeExtensionLanding v-if="tab === 'chrome'" />
<ClawSkillLanding v-if="tab === 'claw'" />
<CliIntegrationLanding v-if="tab === 'cli'" />
@@ -49,6 +57,7 @@ import { useRoute } from 'vue-router'
import IMChannelPanel from '@/components/IMChannelPanel.vue'
import AgentEmbedChannelPanel from '@/components/AgentEmbedChannelPanel.vue'
import ApiIntegrationSettings from '@/views/integrations/ApiIntegrationSettings.vue'
+import McpServerIntegrationSettings from '@/views/integrations/McpServerIntegrationSettings.vue'
import ChromeExtensionLanding from '@/views/integrations/ChromeExtensionLanding.vue'
import ClawSkillLanding from '@/views/integrations/ClawSkillLanding.vue'
import CliIntegrationLanding from '@/views/integrations/CliIntegrationLanding.vue'
diff --git a/frontend/src/views/integrations/McpServerIntegrationSettings.vue b/frontend/src/views/integrations/McpServerIntegrationSettings.vue
new file mode 100644
index 000000000..800fc2a96
--- /dev/null
+++ b/frontend/src/views/integrations/McpServerIntegrationSettings.vue
@@ -0,0 +1,653 @@
+<template>
+ <div class="mcp-server-panel">
+ <div class="channels-section">
+ <div class="channels-header">
+ <span class="channels-title">{{ $t('integrations.mcpserver.listTitle') }}</span>
+ <span class="channels-count">{{ endpoints.length }}</span>
+ </div>
+
+ <t-loading :loading="loading" size="small" class="channels-loading-wrap">
+ <div v-if="!loading && endpoints.length === 0 && !isAdmin" class="channels-empty">
+ <t-empty :description="$t('integrations.mcpserver.empty')" />
+ </div>
+
+ <div v-else-if="!loading" class="channel-grid">
+ <button
+ v-for="ep in endpoints"
+ :key="ep.id"
+ type="button"
+ class="channel-card channel-card--clickable"
+ @click="openEdit(ep)"
+ >
+ <div class="channel-card__badge">
+ <t-icon name="tools" size="22px" />
+ </div>
+ <div class="channel-card__body">
+ <div class="channel-card__header">
+ <h3 class="channel-card__title">{{ ep.name }}</h3>
+ <t-tag v-if="!ep.enabled" size="small" variant="light" theme="warning">
+ {{ $t('integrations.mcpserver.disabled') }}
+ </t-tag>
+ </div>
+ <span class="channel-card__agent-name">
+ {{ $t('integrations.mcpserver.cardSummary', { tools: ep.tools.length, scope: scopeLabel(ep) }) }}
+ </span>
+ </div>
+ <div v-if="isAdmin" class="channel-card__actions" @click.stop>
+ <t-dropdown
+ trigger="click"
+ placement="bottom-right"
+ attach="body"
+ :options="menuOptions(ep)"
+ @click="handleMenuClick($event, ep)"
+ >
+ <t-button variant="text" shape="square" size="small" class="channel-card__action-btn" @click.stop>
+ <template #icon><t-icon name="ellipsis" /></template>
+ </t-button>
+ </t-dropdown>
+ <t-popconfirm
+ :content="$t('integrations.mcpserver.deleteConfirm')"
+ :confirm-btn="{ content: $t('common.delete'), theme: 'danger' }"
+ :cancel-btn="{ content: $t('common.cancel') }"
+ placement="bottom-right"
+ @confirm="() => removeEndpoint(ep)"
+ >
+ <t-tooltip :content="$t('common.delete')" placement="top">
+ <t-button theme="danger" shape="square" variant="text" size="small" class="channel-card__action-btn" @click.stop>
+ <template #icon><t-icon name="delete" /></template>
+ </t-button>
+ </t-tooltip>
+ </t-popconfirm>
+ </div>
+ </button>
+
+ <button v-if="isAdmin" type="button" class="channel-card channel-card--add" @click="openCreate">
+ <span class="channel-card__badge" aria-hidden="true">
+ <t-icon name="add" />
+ </span>
+ <div class="channel-card__body">
+ <div class="channel-card__header">
+ <span class="channel-card__title">{{ $t('integrations.mcpserver.create') }}</span>
+ </div>
+ </div>
+ <span class="channel-card__actions channel-card__actions--spacer" aria-hidden="true" />
+ </button>
+ </div>
+ </t-loading>
+ </div>
+
+ <SettingDrawer
+ v-model:visible="showDrawer"
+ class="mcp-endpoint-drawer"
+ :title="editing ? $t('integrations.mcpserver.editTitle') : $t('integrations.mcpserver.createTitle')"
+ :description="$t('integrations.mcpserver.drawerDesc')"
+ icon="tools"
+ storage-key="setting-drawer:mcp-endpoint"
+ width="600px"
+ :confirm-loading="saving"
+ :confirm-text="editing ? $t('common.save') : $t('integrations.mcpserver.create')"
+ :hide-footer="!isAdmin"
+ @confirm="saveForm"
+ @cancel="closeDrawer"
+ >
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ $t('integrations.mcpserver.sectionBasic') }}</h4>
+ <div class="form-item">
+ <label class="form-label required">{{ $t('integrations.mcpserver.nameLabel') }}</label>
+ <t-input v-model="form.name" :placeholder="$t('integrations.mcpserver.namePlaceholder')" :maxlength="255" />
+ </div>
+ <div class="form-item">
+ <label class="form-label">{{ $t('integrations.mcpserver.descriptionLabel') }}</label>
+ <t-textarea v-model="form.description" :autosize="{ minRows: 2, maxRows: 4 }" :placeholder="$t('integrations.mcpserver.descriptionPlaceholder')" />
+ </div>
+ <div class="form-item enable-row">
+ <label class="form-label form-label--inline">{{ $t('integrations.mcpserver.enabledLabel') }}</label>
+ <t-switch v-model="form.enabled" size="small" />
+ </div>
+ </section>
+
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ $t('integrations.mcpserver.sectionScope') }}</h4>
+ <div class="form-item">
+ <label class="form-label">{{ $t('integrations.mcpserver.kbScopeLabel') }}</label>
+ <t-select
+ v-model="form.knowledge_base_ids"
+ multiple
+ filterable
+ clearable
+ :loading="kbLoading"
+ :options="kbOptions"
+ :placeholder="$t('integrations.mcpserver.kbScopePlaceholder')"
+ />
+ <p class="form-desc">{{ $t('integrations.mcpserver.kbScopeHint') }}</p>
+ </div>
+ </section>
+
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ $t('integrations.mcpserver.sectionTools') }}</h4>
+ <p class="form-desc form-desc--block">{{ $t('integrations.mcpserver.toolsHint') }}</p>
+ <div class="tool-group-list">
+ <div v-for="group in groupedTools" :key="group.group" class="tool-group">
+ <div class="tool-group__header">
+ <span class="tool-group__name">{{ $t(`integrations.mcpserver.groups.${group.group}`) }}</span>
+ <t-button size="small" variant="text" @click="toggleGroup(group, !groupAllSelected(group))">
+ {{ groupAllSelected(group) ? $t('integrations.mcpserver.clearGroup') : $t('integrations.mcpserver.selectGroup') }}
+ </t-button>
+ </div>
+ <div class="tool-group__items">
+ <div v-for="tool in group.tools" :key="tool.name" class="tool-item" :class="{ 'tool-item--danger': tool.destructive }">
+ <t-checkbox :model-value="toolSelections[tool.name] === true" @change="(v: boolean) => setToolSelected(tool.name, v)">
+ <span class="tool-item__label">
+ {{ $t(`integrations.mcpserver.tools.${tool.name}`) }}
+ <code class="tool-item__code">{{ tool.name }}</code>
+ </span>
+ </t-checkbox>
+ <p class="form-desc">{{ $t(`integrations.mcpserver.tools.${tool.name}Desc`) }}</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <p v-if="selectedToolCount === 0" class="form-desc form-desc--error">{{ $t('integrations.mcpserver.toolsRequired') }}</p>
+ </section>
+
+ <section v-if="askSelected" class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ $t('integrations.mcpserver.sectionAsk') }}</h4>
+ <div class="form-item">
+ <label class="form-label">{{ $t('integrations.mcpserver.defaultAgentLabel') }}</label>
+ <t-select
+ v-model="form.default_agent_id"
+ filterable
+ clearable
+ :loading="agentsLoading"
+ :options="agentOptions"
+ :placeholder="$t('integrations.mcpserver.defaultAgentPlaceholder')"
+ />
+ <p class="form-desc">{{ $t('integrations.mcpserver.defaultAgentHint') }}</p>
+ </div>
+ </section>
+
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ $t('integrations.mcpserver.sectionLimits') }}</h4>
+ <div class="form-item">
+ <label class="form-label">{{ $t('integrations.mcpserver.rateLimitLabel') }}</label>
+ <t-input-number v-model="form.rate_limit_per_minute" class="form-number" :min="1" :max="6000" theme="column" />
+ <p class="form-desc">{{ $t('integrations.mcpserver.rateLimitHint') }}</p>
+ </div>
+ </section>
+
+ <section v-if="editing" class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ $t('integrations.mcpserver.sectionConnect') }}</h4>
+ <p class="form-desc form-desc--block">{{ $t('integrations.mcpserver.connectHintExisting', { hint: editing.token_hint }) }}</p>
+ <div class="code-toolbar">
+ <pre class="code-toolbar__code">{{ endpointUrl(editing) }}</pre>
+ <t-button class="code-toolbar__copy" size="small" variant="text" shape="square" :title="$t('common.copy')" @click="copyText(endpointUrl(editing))">
+ <t-icon name="file-copy" size="16px" />
+ </t-button>
+ </div>
+ <t-button size="small" variant="outline" @click="openConnectDialog(editing, '')">
+ {{ $t('integrations.mcpserver.showSnippets') }}
+ </t-button>
+ </section>
+ </SettingDrawer>
+
+ <t-dialog
+ v-model:visible="connectVisible"
+ :header="connectToken ? $t('integrations.mcpserver.tokenDialogTitle') : $t('integrations.mcpserver.connectDialogTitle')"
+ width="640px"
+ :footer="false"
+ :close-on-overlay-click="!connectToken"
+ >
+ <div class="connect-dialog">
+ <t-alert v-if="connectToken" theme="warning" :message="$t('integrations.mcpserver.tokenOnce')" class="connect-dialog__alert" />
+ <p v-else class="form-desc form-desc--block">{{ $t('integrations.mcpserver.connectPlaceholderHint') }}</p>
+
+ <div v-if="connectToken" class="form-item">
+ <label class="form-label">{{ $t('integrations.mcpserver.tokenLabel') }}</label>
+ <div class="code-toolbar">
+ <pre class="code-toolbar__code">{{ connectToken }}</pre>
+ <t-button class="code-toolbar__copy" size="small" variant="text" shape="square" :title="$t('common.copy')" @click="copyText(connectToken)">
+ <t-icon name="file-copy" size="16px" />
+ </t-button>
+ </div>
+ </div>
+
+ <div class="form-item">
+ <label class="form-label">{{ $t('integrations.mcpserver.urlLabel') }}</label>
+ <div class="code-toolbar">
+ <pre class="code-toolbar__code">{{ connectUrl }}</pre>
+ <t-button class="code-toolbar__copy" size="small" variant="text" shape="square" :title="$t('common.copy')" @click="copyText(connectUrl)">
+ <t-icon name="file-copy" size="16px" />
+ </t-button>
+ </div>
+ </div>
+
+ <div v-for="snippet in connectSnippets" :key="snippet.key" class="form-item">
+ <label class="form-label">{{ $t(`integrations.mcpserver.snippet.${snippet.key}Title`) }}</label>
+ <p class="form-desc form-desc--block">{{ $t(`integrations.mcpserver.snippet.${snippet.key}Desc`) }}</p>
+ <div class="code-toolbar">
+ <pre class="code-toolbar__code">{{ snippet.text }}</pre>
+ <t-button class="code-toolbar__copy" size="small" variant="text" shape="square" :title="$t('common.copy')" @click="copyText(snippet.text)">
+ <t-icon name="file-copy" size="16px" />
+ </t-button>
+ </div>
+ </div>
+ </div>
+ </t-dialog>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, onMounted, reactive, ref } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { MessagePlugin } from 'tdesign-vue-next'
+import { useAuthStore } from '@/stores/auth'
+import { copyWithToast } from '@/utils/clipboard'
+import { useApiBaseUrlDisplay } from '@/composables/useApiBaseUrlDisplay'
+import SettingDrawer from '@/components/settings/SettingDrawer.vue'
+import { listAgents, type CustomAgent } from '@/api/agent'
+import { listKnowledgeBases } from '@/api/knowledge-base'
+import {
+ createMcpEndpoint,
+ deleteMcpEndpoint,
+ getMcpEndpointToolCatalog,
+ listMcpEndpoints,
+ rotateMcpEndpointToken,
+ updateMcpEndpoint,
+ type McpEndpoint,
+ type McpEndpointPayload,
+ type McpEndpointToolCatalog,
+} from '@/api/mcp-endpoint'
+import {
+ buildClaudeCodeCommand,
+ buildHttpClientSnippet,
+ buildMcpEndpointUrl,
+ buildStdioBridgeSnippet,
+ groupTools,
+} from './mcpServerIntegration'
+
+const { t } = useI18n()
+const authStore = useAuthStore()
+const { apiBaseUrlDisplay } = useApiBaseUrlDisplay()
+
+const isAdmin = computed(() => authStore.hasRole('admin'))
+
+const loading = ref(false)
+const endpoints = ref<McpEndpoint[]>([])
+const catalog = ref<McpEndpointToolCatalog>({ groups: [], tools: [], default_tools: [] })
+
+const kbLoading = ref(false)
+const knowledgeBases = ref<{ id: string; name: string }[]>([])
+const kbOptions = computed(() => knowledgeBases.value.map((kb) => ({ label: kb.name || kb.id, value: kb.id })))
+const kbNameById = computed(() => Object.fromEntries(knowledgeBases.value.map((kb) => [kb.id, kb.name || kb.id])))
+
+const agentsLoading = ref(false)
+const agents = ref<CustomAgent[]>([])
+const agentOptions = computed(() => agents.value.map((a) => ({ label: a.name, value: a.id })))
+
+const showDrawer = ref(false)
+const saving = ref(false)
+const editing = ref<McpEndpoint | null>(null)
+const form = reactive({
+ name: '',
+ description: '',
+ enabled: true,
+ knowledge_base_ids: [] as string[],
+ default_agent_id: '',
+ rate_limit_per_minute: 60,
+})
+const toolSelections = reactive<Record<string, boolean>>({})
+
+const groupedTools = computed(() => groupTools(catalog.value.groups, catalog.value.tools))
+const selectedToolNames = computed(() => catalog.value.tools.filter((tl) => toolSelections[tl.name]).map((tl) => tl.name))
+const selectedToolCount = computed(() => selectedToolNames.value.length)
+const askSelected = computed(() => toolSelections.ask === true)
+
+const connectVisible = ref(false)
+const connectToken = ref('')
+const connectEndpoint = ref<McpEndpoint | null>(null)
+const connectUrl = computed(() => (connectEndpoint.value ? endpointUrl(connectEndpoint.value) : ''))
+const connectSnippets = computed(() => {
+ const ep = connectEndpoint.value
+ if (!ep) return []
+ const url = endpointUrl(ep)
+ return [
+ { key: 'http', text: buildHttpClientSnippet(ep.name, url, connectToken.value, ep.id) },
+ { key: 'claudeCode', text: buildClaudeCodeCommand(ep.name, url, connectToken.value, ep.id) },
+ { key: 'stdio', text: buildStdioBridgeSnippet(ep.name, url, connectToken.value, ep.id) },
+ ]
+})
+
+function endpointUrl(ep: McpEndpoint): string {
+ return buildMcpEndpointUrl(apiBaseUrlDisplay.value, ep.path)
+}
+
+function scopeLabel(ep: McpEndpoint): string {
+ if (!ep.knowledge_base_ids?.length) return t('integrations.mcpserver.scopeAll')
+ return t('integrations.mcpserver.scopeCount', { count: ep.knowledge_base_ids.length })
+}
+
+function setToolSelected(name: string, selected: boolean) {
+ toolSelections[name] = selected
+}
+
+function groupAllSelected(group: { tools: { name: string }[] }) {
+ return group.tools.every((tl) => toolSelections[tl.name])
+}
+
+function toggleGroup(group: { tools: { name: string }[] }, selected: boolean) {
+ for (const tl of group.tools) toolSelections[tl.name] = selected
+}
+
+function resetForm(ep: McpEndpoint | null) {
+ form.name = ep?.name ?? ''
+ form.description = ep?.description ?? ''
+ form.enabled = ep?.enabled ?? true
+ form.knowledge_base_ids = [...(ep?.knowledge_base_ids ?? [])]
+ form.default_agent_id = ep?.default_agent_id ?? ''
+ form.rate_limit_per_minute = ep?.rate_limit_per_minute || 60
+ const selected = new Set(ep ? ep.tools : catalog.value.default_tools)
+ for (const key of Object.keys(toolSelections)) delete toolSelections[key]
+ for (const tl of catalog.value.tools) toolSelections[tl.name] = selected.has(tl.name)
+}
+
+async function load() {
+ loading.value = true
+ try {
+ const [epRes, catRes] = await Promise.all([listMcpEndpoints(), getMcpEndpointToolCatalog()])
+ endpoints.value = epRes?.data ?? []
+ catalog.value = catRes?.data ?? { groups: [], tools: [], default_tools: [] }
+ } catch (err: any) {
+ MessagePlugin.error(err?.message || t('integrations.mcpserver.loadFailed'))
+ } finally {
+ loading.value = false
+ }
+}
+
+async function loadOptions() {
+ kbLoading.value = true
+ agentsLoading.value = true
+ try {
+ const [kbRes, agentRes] = await Promise.all([
+ listKnowledgeBases({ creator: 'all' }).catch(() => null),
+ listAgents().catch(() => null),
+ ])
+ const kbRows = ((kbRes as any)?.data ?? []) as Array<{ id: string | number; name?: string }>
+ knowledgeBases.value = kbRows.map((kb) => ({ id: String(kb.id), name: kb.name || String(kb.id) }))
+ agents.value = ((agentRes as any)?.data ?? []) as CustomAgent[]
+ } finally {
+ kbLoading.value = false
+ agentsLoading.value = false
+ }
+}
+
+function openCreate() {
+ editing.value = null
+ resetForm(null)
+ showDrawer.value = true
+ void loadOptions()
+}
+
+function openEdit(ep: McpEndpoint) {
+ editing.value = ep
+ resetForm(ep)
+ showDrawer.value = true
+ void loadOptions()
+}
+
+function closeDrawer() {
+ showDrawer.value = false
+}
+
+function buildPayload(): McpEndpointPayload {
+ return {
+ name: form.name.trim(),
+ description: form.description.trim(),
+ enabled: form.enabled,
+ knowledge_base_ids: [...form.knowledge_base_ids],
+ tools: [...selectedToolNames.value],
+ default_agent_id: askSelected.value ? form.default_agent_id : '',
+ rate_limit_per_minute: form.rate_limit_per_minute,
+ }
+}
+
+async function saveForm() {
+ if (!form.name.trim()) {
+ MessagePlugin.warning(t('integrations.mcpserver.nameRequired'))
+ return
+ }
+ if (selectedToolCount.value === 0) {
+ MessagePlugin.warning(t('integrations.mcpserver.toolsRequired'))
+ return
+ }
+ saving.value = true
+ try {
+ const payload = buildPayload()
+ if (editing.value) {
+ await updateMcpEndpoint(editing.value.id, payload)
+ MessagePlugin.success(t('integrations.mcpserver.updated'))
+ showDrawer.value = false
+ await load()
+ } else {
+ const res = await createMcpEndpoint(payload)
+ MessagePlugin.success(t('integrations.mcpserver.created'))
+ showDrawer.value = false
+ await load()
+ if (res?.data) openConnectDialog(res.data, res.data.token || '')
+ }
+ } catch (err: any) {
+ MessagePlugin.error(err?.message || t('integrations.mcpserver.saveFailed'))
+ } finally {
+ saving.value = false
+ }
+}
+
+async function removeEndpoint(ep: McpEndpoint) {
+ try {
+ await deleteMcpEndpoint(ep.id)
+ MessagePlugin.success(t('integrations.mcpserver.deleted'))
+ await load()
+ } catch (err: any) {
+ MessagePlugin.error(err?.message || t('integrations.mcpserver.deleteFailed'))
+ }
+}
+
+async function rotateToken(ep: McpEndpoint) {
+ try {
+ const res = await rotateMcpEndpointToken(ep.id)
+ MessagePlugin.success(t('integrations.mcpserver.rotated'))
+ await load()
+ if (res?.data) openConnectDialog(res.data, res.data.token || '')
+ } catch (err: any) {
+ MessagePlugin.error(err?.message || t('integrations.mcpserver.rotateFailed'))
+ }
+}
+
+async function toggleEnabled(ep: McpEndpoint) {
+ try {
+ await updateMcpEndpoint(ep.id, { enabled: !ep.enabled })
+ MessagePlugin.success(ep.enabled ? t('integrations.mcpserver.disabledToast') : t('integrations.mcpserver.enabledToast'))
+ await load()
+ } catch (err: any) {
+ MessagePlugin.error(err?.message || t('integrations.mcpserver.saveFailed'))
+ }
+}
+
+function openConnectDialog(ep: McpEndpoint, token: string) {
+ connectEndpoint.value = ep
+ connectToken.value = token
+ connectVisible.value = true
+}
+
+function menuOptions(ep: McpEndpoint) {
+ return [
+ { content: t('integrations.mcpserver.menuConnect'), value: 'connect' },
+ { content: ep.enabled ? t('integrations.mcpserver.menuDisable') : t('integrations.mcpserver.menuEnable'), value: 'toggle' },
+ { content: t('integrations.mcpserver.menuRotate'), value: 'rotate' },
+ ]
+}
+
+function handleMenuClick(option: { value?: string | number }, ep: McpEndpoint) {
+ switch (option?.value) {
+ case 'connect':
+ openConnectDialog(ep, '')
+ break
+ case 'toggle':
+ void toggleEnabled(ep)
+ break
+ case 'rotate':
+ void rotateToken(ep)
+ break
+ }
+}
+
+const copyText = (text: string) => copyWithToast(text, 'integrations.mcpserver.copied')
+
+onMounted(() => {
+ void load()
+})
+</script>
+
+<style scoped lang="less">
+@import '../../components/css/channel-panel-list.less';
+
+.mcp-server-panel {
+ display: flex;
+ flex-direction: column;
+}
+
+.form-item {
+ margin-bottom: 0;
+}
+
+.form-label {
+ display: block;
+ margin-bottom: 6px;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--td-text-color-primary);
+ line-height: 1.4;
+
+ &--inline {
+ margin-bottom: 0;
+ }
+
+ &.required::after {
+ content: ' *';
+ color: var(--td-error-color);
+ }
+}
+
+.form-desc {
+ margin: 4px 0 0;
+ font-size: 12px;
+ line-height: 1.45;
+ color: var(--td-text-color-placeholder);
+
+ &--block {
+ margin: -2px 0 0;
+ color: var(--td-text-color-secondary);
+ }
+
+ &--error {
+ color: var(--td-error-color);
+ }
+}
+
+.form-number {
+ width: 100%;
+ max-width: 200px;
+}
+
+.enable-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.tool-group-list {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.tool-group {
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 8px;
+ padding: 10px 12px;
+}
+
+.tool-group__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 6px;
+}
+
+.tool-group__name {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+}
+
+.tool-group__items {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.tool-item {
+ padding-left: 2px;
+
+ .form-desc {
+ margin-left: 24px;
+ }
+
+ &--danger .tool-item__label {
+ color: var(--td-error-color);
+ }
+}
+
+.tool-item__code {
+ margin-left: 6px;
+ font-size: 11px;
+ color: var(--td-text-color-placeholder);
+ background: var(--td-bg-color-secondarycontainer);
+ padding: 1px 5px;
+ border-radius: 4px;
+}
+
+.code-toolbar {
+ position: relative;
+ margin: 6px 0 10px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 8px;
+ background: var(--td-bg-color-secondarycontainer);
+}
+
+.code-toolbar__code {
+ margin: 0;
+ padding: 10px 40px 10px 12px;
+ font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12px;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-all;
+ color: var(--td-text-color-primary);
+}
+
+.code-toolbar__copy {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+}
+
+.connect-dialog {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.connect-dialog__alert {
+ margin-bottom: 4px;
+}
+</style>
diff --git a/frontend/src/views/integrations/mcpServerIntegration.test.ts b/frontend/src/views/integrations/mcpServerIntegration.test.ts
new file mode 100644
index 000000000..e03f8577b
--- /dev/null
+++ b/frontend/src/views/integrations/mcpServerIntegration.test.ts
@@ -0,0 +1,57 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ buildClaudeCodeCommand,
+ buildHttpClientSnippet,
+ buildMcpEndpointUrl,
+ buildStdioBridgeSnippet,
+ groupTools,
+ mcpServerKey,
+ MCP_TOKEN_PLACEHOLDER,
+} from './mcpServerIntegration'
+
+test('buildMcpEndpointUrl strips the api prefix and joins the endpoint path', () => {
+ assert.equal(buildMcpEndpointUrl('https://kb.example.com/api/v1', '/mcp/abc'), 'https://kb.example.com/mcp/abc')
+ assert.equal(buildMcpEndpointUrl('https://kb.example.com/api/v1/', 'mcp/abc'), 'https://kb.example.com/mcp/abc')
+ assert.equal(buildMcpEndpointUrl('http://localhost:8080', '/mcp/x'), 'http://localhost:8080/mcp/x')
+})
+
+test('mcpServerKey slugs the endpoint name', () => {
+ assert.equal(mcpServerKey('Docs Bot!'), 'weknora-docs-bot')
+ assert.equal(mcpServerKey(' '), 'weknora')
+ assert.equal(mcpServerKey('产品知识库'), 'weknora')
+ assert.equal(mcpServerKey('产品知识库', '3f9a2c1e-aaaa'), 'weknora-3f9a2c1e')
+ assert.notEqual(mcpServerKey('知识库A', 'id-one'), mcpServerKey('知识库B', 'id-two'))
+})
+
+test('http snippet carries url and bearer header', () => {
+ const parsed = JSON.parse(buildHttpClientSnippet('Docs', 'https://h/mcp/1', 'mcp_t'))
+ assert.deepEqual(parsed, {
+ mcpServers: { 'weknora-docs': { url: 'https://h/mcp/1', headers: { Authorization: 'Bearer mcp_t' } } },
+ })
+})
+
+test('snippets fall back to a placeholder when no token is known', () => {
+ assert.match(buildHttpClientSnippet('a', 'u', ''), new RegExp(MCP_TOKEN_PLACEHOLDER))
+ assert.match(buildClaudeCodeCommand('a', 'u', ''), new RegExp(MCP_TOKEN_PLACEHOLDER))
+ const bridge = JSON.parse(buildStdioBridgeSnippet('a', 'https://h/mcp/1', ''))
+ assert.equal(bridge.mcpServers['weknora-a'].command, 'npx')
+ assert.ok(bridge.mcpServers['weknora-a'].args.includes('https://h/mcp/1'))
+})
+
+test('claude code command uses the http transport', () => {
+ assert.equal(
+ buildClaudeCodeCommand('Docs', 'https://h/mcp/1', 'mcp_t'),
+ 'claude mcp add --transport http weknora-docs https://h/mcp/1 --header "Authorization: Bearer mcp_t"',
+ )
+})
+
+test('groupTools keeps backend order and drops empty groups', () => {
+ const grouped = groupTools(['retrieve', 'chat', 'wiki', 'ingest'], [
+ { name: 'ask', group: 'chat', destructive: false },
+ { name: 'search_knowledge', group: 'retrieve', destructive: false },
+ { name: 'delete_document', group: 'ingest', destructive: true },
+ ])
+ assert.deepEqual(grouped.map((g) => g.group), ['retrieve', 'chat', 'ingest'])
+ assert.deepEqual(grouped[0].tools.map((t) => t.name), ['search_knowledge'])
+})
diff --git a/frontend/src/views/integrations/mcpServerIntegration.ts b/frontend/src/views/integrations/mcpServerIntegration.ts
new file mode 100644
index 000000000..64a292067
--- /dev/null
+++ b/frontend/src/views/integrations/mcpServerIntegration.ts
@@ -0,0 +1,98 @@
+/**
+ * Pure helpers for the "WeKnora as MCP server" integration page. Kept free
+ * of Vue so the snippet builders can be unit-tested with node:test.
+ */
+
+export const MCP_TOKEN_PLACEHOLDER = '<YOUR_TOKEN>'
+
+/**
+ * Derive the public MCP URL from the displayed API base (".../api/v1") and
+ * the endpoint path ("/mcp/<id>") returned by the backend.
+ */
+export function buildMcpEndpointUrl(apiBaseUrl: string, endpointPath: string): string {
+ const base = (apiBaseUrl || '').trim().replace(/\/+$/, '').replace(/\/api\/v1$/, '')
+ const path = endpointPath.startsWith('/') ? endpointPath : `/${endpointPath}`
+ return `${base}${path}`
+}
+
+/**
+ * Sanitize an endpoint name into an mcpServers key. Names that leave no
+ * ASCII characters (e.g. Chinese) fall back to the endpoint id so two such
+ * endpoints never collide in the client configuration.
+ */
+export function mcpServerKey(name: string, id = ''): string {
+ const slug = (name || '')
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ if (slug) return `weknora-${slug}`
+ const idSlug = (id || '').replace(/[^a-z0-9]/gi, '').slice(0, 8).toLowerCase()
+ return idSlug ? `weknora-${idSlug}` : 'weknora'
+}
+
+/** JSON block for clients that speak Streamable HTTP natively (Cursor, VS Code, Claude Desktop connectors). */
+export function buildHttpClientSnippet(name: string, url: string, token: string, id = ''): string {
+ return JSON.stringify(
+ {
+ mcpServers: {
+ [mcpServerKey(name, id)]: {
+ url,
+ headers: { Authorization: `Bearer ${token || MCP_TOKEN_PLACEHOLDER}` },
+ },
+ },
+ },
+ null,
+ 2,
+ )
+}
+
+/** One-liner for Claude Code. */
+export function buildClaudeCodeCommand(name: string, url: string, token: string, id = ''): string {
+ const auth = `Authorization: Bearer ${token || MCP_TOKEN_PLACEHOLDER}`
+ return `claude mcp add --transport http ${mcpServerKey(name, id)} ${url} --header "${auth}"`
+}
+
+/** JSON block for stdio-only clients, bridged through mcp-remote. */
+export function buildStdioBridgeSnippet(name: string, url: string, token: string, id = ''): string {
+ return JSON.stringify(
+ {
+ mcpServers: {
+ [mcpServerKey(name, id)]: {
+ command: 'npx',
+ args: ['-y', 'mcp-remote', url, '--header', `Authorization: Bearer ${token || MCP_TOKEN_PLACEHOLDER}`],
+ },
+ },
+ },
+ null,
+ 2,
+ )
+}
+
+export interface ToolCatalogEntry {
+ name: string
+ group: string
+ destructive: boolean
+}
+
+export interface GroupedTools<T extends ToolCatalogEntry> {
+ group: string
+ tools: T[]
+}
+
+/** Group catalog entries in the backend's group order, dropping empty groups. */
+export function groupTools<T extends ToolCatalogEntry>(groups: string[], tools: T[]): GroupedTools<T>[] {
+ const known = new Set(groups)
+ const order = [...groups, ...tools.map((t) => t.group).filter((g) => !known.has(g))]
+ const out: GroupedTools<T>[] = []
+ for (const group of Array.from(new Set(order))) {
+ const members = tools.filter((t) => t.group === group)
+ if (members.length > 0) out.push({ group, tools: members })
+ }
+ return out
+}
+
+/** Summarize a knowledge-base scope for the card: empty means "all". */
+export function summarizeScope(ids: string[] | null | undefined, names: Record<string, string>): string[] {
+ return (ids || []).map((id) => names[id] || id)
+}
diff --git a/internal/application/repository/mcp_endpoint.go b/internal/application/repository/mcp_endpoint.go
new file mode 100644
index 000000000..e383cdb82
--- /dev/null
+++ b/internal/application/repository/mcp_endpoint.go
@@ -0,0 +1,78 @@
+package repository
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "gorm.io/gorm"
+)
+
+type mcpEndpointRepository struct {
+ db *gorm.DB
+}
+
+// NewMCPEndpointRepository creates a GORM-backed MCP endpoint repository.
+func NewMCPEndpointRepository(db *gorm.DB) interfaces.MCPEndpointRepository {
+ return &mcpEndpointRepository{db: db}
+}
+
+func (r *mcpEndpointRepository) Create(ctx context.Context, ep *types.MCPEndpoint) error {
+ return r.db.WithContext(ctx).Create(ep).Error
+}
+
+func (r *mcpEndpointRepository) GetByID(ctx context.Context, id string) (*types.MCPEndpoint, error) {
+ var ep types.MCPEndpoint
+ err := r.db.WithContext(ctx).Where("id = ?", id).First(&ep).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &ep, nil
+}
+
+func (r *mcpEndpointRepository) GetByTokenHash(ctx context.Context, tokenHash string) (*types.MCPEndpoint, error) {
+ if tokenHash == "" {
+ return nil, nil
+ }
+ var ep types.MCPEndpoint
+ err := r.db.WithContext(ctx).Where("token_hash = ?", tokenHash).First(&ep).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &ep, nil
+}
+
+func (r *mcpEndpointRepository) ListByTenant(ctx context.Context, tenantID uint64) ([]*types.MCPEndpoint, error) {
+ var rows []*types.MCPEndpoint
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ?", tenantID).
+ Order("created_at DESC").
+ Find(&rows).Error
+ return rows, err
+}
+
+func (r *mcpEndpointRepository) Update(ctx context.Context, ep *types.MCPEndpoint) error {
+ return r.db.WithContext(ctx).Save(ep).Error
+}
+
+func (r *mcpEndpointRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
+ return r.db.WithContext(ctx).
+ Where("tenant_id = ? AND id = ?", tenantID, id).
+ Delete(&types.MCPEndpoint{}).Error
+}
+
+func (r *mcpEndpointRepository) TouchLastUsed(ctx context.Context, id string) error {
+ now := time.Now()
+ return r.db.WithContext(ctx).
+ Model(&types.MCPEndpoint{}).
+ Where("id = ?", id).
+ UpdateColumn("last_used_at", now).Error
+}
diff --git a/internal/application/service/mcp_endpoint.go b/internal/application/service/mcp_endpoint.go
new file mode 100644
index 000000000..53a0ab8bb
--- /dev/null
+++ b/internal/application/service/mcp_endpoint.go
@@ -0,0 +1,319 @@
+package service
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/application/access"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+var (
+ // ErrMCPEndpointNotFound is returned when an endpoint does not exist or
+ // belongs to another workspace; the two cases are deliberately
+ // indistinguishable to callers.
+ ErrMCPEndpointNotFound = errors.New("mcp endpoint not found")
+ // ErrMCPEndpointDisabled is returned when an otherwise valid token targets
+ // an endpoint that has been switched off.
+ ErrMCPEndpointDisabled = errors.New("mcp endpoint disabled")
+ // ErrMCPEndpointTokenInvalid is returned when the bearer token does not
+ // resolve to the addressed endpoint.
+ ErrMCPEndpointTokenInvalid = errors.New("mcp endpoint token invalid")
+)
+
+const (
+ mcpEndpointTokenBytes = 32
+ mcpEndpointTokenHintLen = 12
+ mcpEndpointMaxNameLen = 255
+ mcpEndpointMaxRatePerMin = 6000
+)
+
+type mcpEndpointService struct {
+ repo interfaces.MCPEndpointRepository
+ kbService interfaces.KnowledgeBaseService
+ kbShareService interfaces.KBShareService
+ agentService interfaces.CustomAgentService
+}
+
+// NewMCPEndpointService creates the workspace MCP endpoint service.
+func NewMCPEndpointService(
+ repo interfaces.MCPEndpointRepository,
+ kbService interfaces.KnowledgeBaseService,
+ kbShareService interfaces.KBShareService,
+ agentService interfaces.CustomAgentService,
+) interfaces.MCPEndpointService {
+ return &mcpEndpointService{
+ repo: repo,
+ kbService: kbService,
+ kbShareService: kbShareService,
+ agentService: agentService,
+ }
+}
+
+func generateMCPEndpointToken() (string, error) {
+ buf := make([]byte, mcpEndpointTokenBytes)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return types.MCPEndpointTokenPrefix + base64.RawURLEncoding.EncodeToString(buf), nil
+}
+
+// HashMCPEndpointToken returns the storage digest of a plaintext token.
+func HashMCPEndpointToken(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
+func mcpEndpointTokenHint(token string) string {
+ if len(token) <= mcpEndpointTokenHintLen {
+ return token
+ }
+ return token[:mcpEndpointTokenHintLen]
+}
+
+func (s *mcpEndpointService) Create(
+ ctx context.Context, tenantID uint64, ep *types.MCPEndpoint,
+) (*types.MCPEndpoint, string, error) {
+ if ep == nil {
+ return nil, "", apperrors.NewBadRequestError("endpoint is required")
+ }
+ name := strings.TrimSpace(ep.Name)
+ if name == "" {
+ return nil, "", apperrors.NewBadRequestError("name is required")
+ }
+ if len(name) > mcpEndpointMaxNameLen {
+ return nil, "", apperrors.NewBadRequestError("name is too long")
+ }
+ tools := types.NormalizeMCPEndpointTools(ep.Tools)
+ if len(tools) == 0 {
+ return nil, "", apperrors.NewBadRequestError("at least one tool must be enabled")
+ }
+ kbIDs, err := s.validateKnowledgeBases(ctx, tenantID, ep.KnowledgeBaseIDs)
+ if err != nil {
+ return nil, "", err
+ }
+ agentID, err := s.validateAgent(ctx, tenantID, ep.DefaultAgentID)
+ if err != nil {
+ return nil, "", err
+ }
+ rate, err := normalizeMCPEndpointRate(ep.RateLimitPerMinute)
+ if err != nil {
+ return nil, "", err
+ }
+ token, err := generateMCPEndpointToken()
+ if err != nil {
+ return nil, "", err
+ }
+ row := &types.MCPEndpoint{
+ TenantID: tenantID,
+ Name: name,
+ Description: strings.TrimSpace(ep.Description),
+ Enabled: ep.Enabled,
+ TokenHash: HashMCPEndpointToken(token),
+ TokenHint: mcpEndpointTokenHint(token),
+ KnowledgeBaseIDs: types.StringArray(kbIDs),
+ Tools: types.StringArray(tools),
+ DefaultAgentID: agentID,
+ RateLimitPerMinute: rate,
+ }
+ if err := s.repo.Create(ctx, row); err != nil {
+ return nil, "", err
+ }
+ return row, token, nil
+}
+
+func (s *mcpEndpointService) Get(ctx context.Context, tenantID uint64, id string) (*types.MCPEndpoint, error) {
+ return s.getOwned(ctx, tenantID, id)
+}
+
+func (s *mcpEndpointService) List(ctx context.Context, tenantID uint64) ([]*types.MCPEndpoint, error) {
+ return s.repo.ListByTenant(ctx, tenantID)
+}
+
+func (s *mcpEndpointService) Update(
+ ctx context.Context, tenantID uint64, id string, upd interfaces.MCPEndpointUpdate,
+) (*types.MCPEndpoint, error) {
+ ep, err := s.getOwned(ctx, tenantID, id)
+ if err != nil {
+ return nil, err
+ }
+ if upd.Name != nil {
+ name := strings.TrimSpace(*upd.Name)
+ if name == "" {
+ return nil, apperrors.NewBadRequestError("name is required")
+ }
+ if len(name) > mcpEndpointMaxNameLen {
+ return nil, apperrors.NewBadRequestError("name is too long")
+ }
+ ep.Name = name
+ }
+ if upd.Description != nil {
+ ep.Description = strings.TrimSpace(*upd.Description)
+ }
+ if upd.Enabled != nil {
+ ep.Enabled = *upd.Enabled
+ }
+ if upd.Tools != nil {
+ tools := types.NormalizeMCPEndpointTools(*upd.Tools)
+ if len(tools) == 0 {
+ return nil, apperrors.NewBadRequestError("at least one tool must be enabled")
+ }
+ ep.Tools = types.StringArray(tools)
+ }
+ if upd.KnowledgeBaseIDs != nil {
+ kbIDs, err := s.validateKnowledgeBases(ctx, tenantID, *upd.KnowledgeBaseIDs)
+ if err != nil {
+ return nil, err
+ }
+ ep.KnowledgeBaseIDs = types.StringArray(kbIDs)
+ }
+ if upd.DefaultAgentID != nil {
+ agentID, err := s.validateAgent(ctx, tenantID, *upd.DefaultAgentID)
+ if err != nil {
+ return nil, err
+ }
+ ep.DefaultAgentID = agentID
+ }
+ if upd.RateLimitPerMinute != nil {
+ rate, err := normalizeMCPEndpointRate(*upd.RateLimitPerMinute)
+ if err != nil {
+ return nil, err
+ }
+ ep.RateLimitPerMinute = rate
+ }
+ if err := s.repo.Update(ctx, ep); err != nil {
+ return nil, err
+ }
+ return ep, nil
+}
+
+func (s *mcpEndpointService) Delete(ctx context.Context, tenantID uint64, id string) error {
+ if _, err := s.getOwned(ctx, tenantID, id); err != nil {
+ return err
+ }
+ return s.repo.Delete(ctx, tenantID, id)
+}
+
+func (s *mcpEndpointService) RotateToken(
+ ctx context.Context, tenantID uint64, id string,
+) (*types.MCPEndpoint, string, error) {
+ ep, err := s.getOwned(ctx, tenantID, id)
+ if err != nil {
+ return nil, "", err
+ }
+ token, err := generateMCPEndpointToken()
+ if err != nil {
+ return nil, "", err
+ }
+ ep.TokenHash = HashMCPEndpointToken(token)
+ ep.TokenHint = mcpEndpointTokenHint(token)
+ if err := s.repo.Update(ctx, ep); err != nil {
+ return nil, "", err
+ }
+ return ep, token, nil
+}
+
+func (s *mcpEndpointService) Authenticate(
+ ctx context.Context, endpointID, token string,
+) (*types.MCPEndpoint, error) {
+ endpointID = strings.TrimSpace(endpointID)
+ token = strings.TrimSpace(token)
+ if endpointID == "" || token == "" || !strings.HasPrefix(token, types.MCPEndpointTokenPrefix) {
+ return nil, ErrMCPEndpointTokenInvalid
+ }
+ ep, err := s.repo.GetByTokenHash(ctx, HashMCPEndpointToken(token))
+ if err != nil {
+ return nil, err
+ }
+ // Compare the addressed endpoint id in constant time so a token for one
+ // endpoint cannot be probed against another by timing.
+ if ep == nil || subtle.ConstantTimeCompare([]byte(ep.ID), []byte(endpointID)) != 1 {
+ return nil, ErrMCPEndpointTokenInvalid
+ }
+ if !ep.Enabled {
+ return nil, ErrMCPEndpointDisabled
+ }
+ return ep, nil
+}
+
+func (s *mcpEndpointService) getOwned(ctx context.Context, tenantID uint64, id string) (*types.MCPEndpoint, error) {
+ ep, err := s.repo.GetByID(ctx, strings.TrimSpace(id))
+ if err != nil {
+ return nil, err
+ }
+ if ep == nil || ep.TenantID != tenantID {
+ return nil, ErrMCPEndpointNotFound
+ }
+ return ep, nil
+}
+
+// validateKnowledgeBases confirms every ID names a knowledge base the
+// workspace owns or has been granted through an organization share, and
+// returns the deduplicated list. The lookup is tenant-agnostic on purpose so
+// that shared knowledge bases resolve; authorization is then decided by
+// access.ResolveKB for the calling principal, never inferred from the ID.
+func (s *mcpEndpointService) validateKnowledgeBases(
+ ctx context.Context, tenantID uint64, ids []string,
+) ([]string, error) {
+ caller := types.CallerFromContext(ctx)
+ if caller.TenantID == 0 {
+ caller.TenantID = tenantID
+ }
+ if caller.TenantID != tenantID {
+ return nil, apperrors.NewForbiddenError("caller does not belong to this workspace")
+ }
+ out := make([]string, 0, len(ids))
+ seen := map[string]struct{}{}
+ for _, raw := range ids {
+ id := strings.TrimSpace(raw)
+ if id == "" {
+ continue
+ }
+ if _, dup := seen[id]; dup {
+ continue
+ }
+ kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, id)
+ if err != nil || kb == nil {
+ return nil, apperrors.NewNotFoundError("knowledge base not found: " + id)
+ }
+ if _, err := access.ResolveKB(ctx, access.KBRequest{Caller: caller}, kb,
+ types.OrgRoleViewer, s.kbShareService, nil); err != nil {
+ return nil, apperrors.NewNotFoundError("knowledge base not found: " + id)
+ }
+ seen[id] = struct{}{}
+ out = append(out, id)
+ }
+ return out, nil
+}
+
+// validateAgent accepts a tenant-owned agent or a user-facing builtin. The
+// same rule is applied again at call time by the MCP server.
+func (s *mcpEndpointService) validateAgent(ctx context.Context, tenantID uint64, agentID string) (string, error) {
+ agentID = strings.TrimSpace(agentID)
+ if agentID == "" {
+ return "", nil
+ }
+ agent, err := s.agentService.GetAgentByID(ctx, agentID)
+ if err != nil || agent == nil || !types.MCPEndpointAgentAllowed(agent, tenantID) {
+ return "", apperrors.NewNotFoundError("agent not found")
+ }
+ return agentID, nil
+}
+
+func normalizeMCPEndpointRate(rate int) (int, error) {
+ if rate == 0 {
+ return types.DefaultMCPEndpointRateLimitPerMinute, nil
+ }
+ if rate < 0 || rate > mcpEndpointMaxRatePerMin {
+ return 0, apperrors.NewBadRequestError("rate_limit_per_minute is out of range")
+ }
+ return rate, nil
+}
diff --git a/internal/application/service/mcp_endpoint_test.go b/internal/application/service/mcp_endpoint_test.go
new file mode 100644
index 000000000..6a066a12f
--- /dev/null
+++ b/internal/application/service/mcp_endpoint_test.go
@@ -0,0 +1,271 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+type stubMCPEndpointRepo struct {
+ interfaces.MCPEndpointRepository
+ rows map[string]*types.MCPEndpoint
+}
+
+func newStubMCPEndpointRepo() *stubMCPEndpointRepo {
+ return &stubMCPEndpointRepo{rows: map[string]*types.MCPEndpoint{}}
+}
+
+func (r *stubMCPEndpointRepo) Create(_ context.Context, ep *types.MCPEndpoint) error {
+ if ep.ID == "" {
+ ep.ID = "ep-" + ep.Name
+ }
+ cp := *ep
+ r.rows[ep.ID] = &cp
+ return nil
+}
+
+func (r *stubMCPEndpointRepo) GetByID(_ context.Context, id string) (*types.MCPEndpoint, error) {
+ ep, ok := r.rows[id]
+ if !ok {
+ return nil, nil
+ }
+ cp := *ep
+ return &cp, nil
+}
+
+func (r *stubMCPEndpointRepo) GetByTokenHash(_ context.Context, hash string) (*types.MCPEndpoint, error) {
+ for _, ep := range r.rows {
+ if ep.TokenHash == hash {
+ cp := *ep
+ return &cp, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *stubMCPEndpointRepo) Update(_ context.Context, ep *types.MCPEndpoint) error {
+ cp := *ep
+ r.rows[ep.ID] = &cp
+ return nil
+}
+
+func (r *stubMCPEndpointRepo) Delete(_ context.Context, tenantID uint64, id string) error {
+ if ep, ok := r.rows[id]; ok && ep.TenantID == tenantID {
+ delete(r.rows, id)
+ }
+ return nil
+}
+
+func newMCPEndpointServiceForTest(repo *stubMCPEndpointRepo, agent *types.CustomAgent) *mcpEndpointService {
+ return &mcpEndpointService{
+ repo: repo,
+ agentService: &stubAgentForEmbed{agent: agent},
+ }
+}
+
+func TestMCPEndpointCreateIssuesHashedToken(t *testing.T) {
+ repo := newStubMCPEndpointRepo()
+ svc := newMCPEndpointServiceForTest(repo, nil)
+
+ ep, token, err := svc.Create(context.Background(), 7, &types.MCPEndpoint{
+ Name: " Docs bot ",
+ Enabled: true,
+ Tools: types.StringArray{"bogus", types.MCPEndpointToolAsk, types.MCPEndpointToolSearchKnowledge},
+ })
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if !strings.HasPrefix(token, types.MCPEndpointTokenPrefix) {
+ t.Fatalf("token %q lacks prefix", token)
+ }
+ if ep.TokenHash != HashMCPEndpointToken(token) || ep.TokenHash == token {
+ t.Fatal("token must be stored hashed")
+ }
+ if ep.Name != "Docs bot" || ep.TenantID != 7 ||
+ ep.RateLimitPerMinute != types.DefaultMCPEndpointRateLimitPerMinute {
+ t.Fatalf("unexpected row %+v", ep)
+ }
+ toolNames := []string(ep.Tools)
+ if len(toolNames) != 2 || toolNames[0] != types.MCPEndpointToolSearchKnowledge ||
+ toolNames[1] != types.MCPEndpointToolAsk {
+ t.Fatalf("tools not normalized: %v", toolNames)
+ }
+ if !strings.HasPrefix(token, ep.TokenHint) {
+ t.Fatalf("hint %q is not a prefix of token", ep.TokenHint)
+ }
+
+ got, err := svc.Authenticate(context.Background(), ep.ID, token)
+ if err != nil || got == nil || got.ID != ep.ID {
+ t.Fatalf("authenticate: %v %v", got, err)
+ }
+ _, err = svc.Authenticate(context.Background(), "other-endpoint", token)
+ if !errors.Is(err, ErrMCPEndpointTokenInvalid) {
+ t.Fatalf("token must be bound to its endpoint id, got %v", err)
+ }
+ _, err = svc.Authenticate(context.Background(), ep.ID, "sk-not-an-endpoint-token")
+ if !errors.Is(err, ErrMCPEndpointTokenInvalid) {
+ t.Fatalf("foreign token prefix must be rejected, got %v", err)
+ }
+}
+
+func TestMCPEndpointCreateValidation(t *testing.T) {
+ svc := newMCPEndpointServiceForTest(newStubMCPEndpointRepo(), nil)
+ _, _, err := svc.Create(context.Background(), 1, &types.MCPEndpoint{Name: "", Tools: types.StringArray{"ask"}})
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrBadRequest {
+ t.Fatalf("empty name must be a bad request, got %v", err)
+ }
+ _, _, err = svc.Create(context.Background(), 1, &types.MCPEndpoint{Name: "x", Tools: types.StringArray{"bogus"}})
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrBadRequest {
+ t.Fatalf("no valid tools must be a bad request, got %v", err)
+ }
+ _, _, err = svc.Create(context.Background(), 1, &types.MCPEndpoint{
+ Name: "x", Tools: types.StringArray{"ask"}, RateLimitPerMinute: -5,
+ })
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrBadRequest {
+ t.Fatalf("negative rate must be a bad request, got %v", err)
+ }
+}
+
+func TestMCPEndpointDefaultAgentMustBelongToTenant(t *testing.T) {
+ foreign := &types.CustomAgent{ID: "agent-1", TenantID: 99}
+ svc := newMCPEndpointServiceForTest(newStubMCPEndpointRepo(), foreign)
+ _, _, err := svc.Create(context.Background(), 1, &types.MCPEndpoint{
+ Name: "x", Tools: types.StringArray{"ask"}, DefaultAgentID: "agent-1",
+ })
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrNotFound {
+ t.Fatalf("foreign agent must be rejected as not found, got %v", err)
+ }
+
+ builtin := &types.CustomAgent{ID: types.BuiltinQuickAnswerID, TenantID: 99, IsBuiltin: true}
+ svc = newMCPEndpointServiceForTest(newStubMCPEndpointRepo(), builtin)
+ if _, _, err := svc.Create(context.Background(), 1, &types.MCPEndpoint{
+ Name: "x", Tools: types.StringArray{"ask"}, DefaultAgentID: types.BuiltinQuickAnswerID,
+ }); err != nil {
+ t.Fatalf("builtin agent must be accepted: %v", err)
+ }
+}
+
+func TestMCPEndpointUpdateRotateDeleteAreTenantScoped(t *testing.T) {
+ repo := newStubMCPEndpointRepo()
+ svc := newMCPEndpointServiceForTest(repo, nil)
+ ep, token, err := svc.Create(context.Background(), 1, &types.MCPEndpoint{
+ Name: "x", Enabled: true, Tools: types.StringArray{"ask"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ _, err = svc.Update(context.Background(), 2, ep.ID, interfaces.MCPEndpointUpdate{})
+ if !errors.Is(err, ErrMCPEndpointNotFound) {
+ t.Fatalf("other tenant must not see the endpoint, got %v", err)
+ }
+ disabled := false
+ name := "renamed"
+ tools := []string{types.MCPEndpointToolSearchKnowledge, "bogus"}
+ updated, err := svc.Update(context.Background(), 1, ep.ID, interfaces.MCPEndpointUpdate{
+ Name: &name, Enabled: &disabled, Tools: &tools,
+ })
+ if err != nil {
+ t.Fatalf("update: %v", err)
+ }
+ if updated.Name != "renamed" || updated.Enabled || len(updated.Tools) != 1 {
+ t.Fatalf("update not applied: %+v", updated)
+ }
+ if _, err := svc.Authenticate(context.Background(), ep.ID, token); !errors.Is(err, ErrMCPEndpointDisabled) {
+ t.Fatalf("disabled endpoint must reject calls, got %v", err)
+ }
+
+ empty := []string{}
+ if _, err := svc.Update(context.Background(), 1, ep.ID, interfaces.MCPEndpointUpdate{Tools: &empty}); err == nil {
+ t.Fatal("clearing every tool must be rejected")
+ }
+
+ rotated, newToken, err := svc.RotateToken(context.Background(), 1, ep.ID)
+ if err != nil {
+ t.Fatalf("rotate: %v", err)
+ }
+ if newToken == token || rotated.TokenHash == ep.TokenHash {
+ t.Fatal("rotate must issue a fresh token")
+ }
+ enabled := true
+ _, err = svc.Update(context.Background(), 1, ep.ID, interfaces.MCPEndpointUpdate{Enabled: &enabled})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := svc.Authenticate(context.Background(), ep.ID, token); !errors.Is(err, ErrMCPEndpointTokenInvalid) {
+ t.Fatalf("old token must stop working after rotation, got %v", err)
+ }
+ if got, err := svc.Authenticate(context.Background(), ep.ID, newToken); err != nil || got.ID != ep.ID {
+ t.Fatalf("new token must work: %v %v", got, err)
+ }
+
+ if err := svc.Delete(context.Background(), 2, ep.ID); !errors.Is(err, ErrMCPEndpointNotFound) {
+ t.Fatalf("delete by other tenant must be not found, got %v", err)
+ }
+ if err := svc.Delete(context.Background(), 1, ep.ID); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ if _, err := svc.Get(context.Background(), 1, ep.ID); !errors.Is(err, ErrMCPEndpointNotFound) {
+ t.Fatalf("deleted endpoint must be gone, got %v", err)
+ }
+}
+
+type stubKBForMCPEndpoint struct {
+ interfaces.KnowledgeBaseService
+ kbs map[string]*types.KnowledgeBase
+}
+
+func (s *stubKBForMCPEndpoint) GetKnowledgeBaseByIDOnly(_ context.Context, id string) (*types.KnowledgeBase, error) {
+ kb, ok := s.kbs[id]
+ if !ok {
+ return nil, errors.New("not found")
+ }
+ return kb, nil
+}
+
+func TestMCPEndpointKnowledgeBaseScopeIsTenantIsolated(t *testing.T) {
+ svc := &mcpEndpointService{
+ repo: newStubMCPEndpointRepo(),
+ kbService: &stubKBForMCPEndpoint{kbs: map[string]*types.KnowledgeBase{
+ "kb-own": {ID: "kb-own", TenantID: 1, Name: "Own"},
+ "kb-foreign": {ID: "kb-foreign", TenantID: 2, Name: "Foreign"},
+ }},
+ }
+ ctx := types.WithCaller(context.Background(), types.Caller{TenantID: 1, UserID: "u1", Role: types.TenantRoleAdmin})
+
+ if _, _, err := svc.Create(ctx, 1, &types.MCPEndpoint{
+ Name: "x", Tools: types.StringArray{"ask"}, KnowledgeBaseIDs: types.StringArray{"kb-own"},
+ }); err != nil {
+ t.Fatalf("own knowledge base must be accepted: %v", err)
+ }
+
+ _, _, err := svc.Create(ctx, 1, &types.MCPEndpoint{
+ Name: "x", Tools: types.StringArray{"ask"}, KnowledgeBaseIDs: types.StringArray{"kb-foreign"},
+ })
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrNotFound {
+ t.Fatalf("another workspace's knowledge base must be rejected, got %v", err)
+ }
+
+ _, _, err = svc.Create(ctx, 1, &types.MCPEndpoint{
+ Name: "x", Tools: types.StringArray{"ask"}, KnowledgeBaseIDs: types.StringArray{"kb-missing"},
+ })
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrNotFound {
+ t.Fatalf("unknown knowledge base must be rejected, got %v", err)
+ }
+}
+
+func TestMCPEndpointRejectsInternalBuiltinAgent(t *testing.T) {
+ hidden := &types.CustomAgent{ID: types.BuiltinWikiFixerID, TenantID: 1, IsBuiltin: true}
+ svc := newMCPEndpointServiceForTest(newStubMCPEndpointRepo(), hidden)
+ _, _, err := svc.Create(context.Background(), 1, &types.MCPEndpoint{
+ Name: "x", Tools: types.StringArray{"ask"}, DefaultAgentID: types.BuiltinWikiFixerID,
+ })
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrNotFound {
+ t.Fatalf("internal builtin agent must be rejected, got %v", err)
+ }
+}
diff --git a/internal/container/container.go b/internal/container/container.go
index caa6a6117..16bd7df0a 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -83,6 +83,7 @@ import (
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/mcp"
+ "github.com/Tencent/WeKnora/internal/mcpserver"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/limiter"
@@ -175,6 +176,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewKBShareRepository))
must(container.Provide(repository.NewAgentShareRepository))
must(container.Provide(repository.NewEmbedChannelRepository))
+ must(container.Provide(repository.NewMCPEndpointRepository))
must(container.Provide(repository.NewTenantDisabledSharedAgentRepository))
must(container.Provide(repository.NewUserResourceFavoriteRepository))
must(container.Provide(service.NewWebSearchStateService))
@@ -265,6 +267,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewWikiIngestService, dig.Name("wikiIngest")))
must(container.Provide(service.NewWikiLintService))
must(container.Provide(service.NewEmbedChannelService))
+ must(container.Provide(service.NewMCPEndpointService))
+ must(container.Provide(mcpserver.NewServer))
// Web search service (needed by AgentService)
logger.Debugf(ctx, "[Container] Registering web search registry and providers...")
@@ -539,6 +543,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(registerIMService))
must(container.Provide(handler.NewIMHandler))
must(container.Provide(handler.NewEmbedChannelHandler))
+ must(container.Provide(handler.NewMCPEndpointHandler))
must(container.Provide(handler.NewWeKnoraCloudHandler))
logger.Debugf(ctx, "[Container] HTTP handlers registered")
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index ded50b489..6ea1da70b 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -26,6 +26,7 @@ var versionedSQLiteTables = []string{
"browser_pairings",
"browser_task_interruptions",
"fork_snapshot_leases",
+ "mcp_endpoints",
}
// versionedSQLiteColumns maps each existing table to the columns that the
@@ -45,7 +46,7 @@ var versionedSQLiteColumns = map[string][]string{
"mcp_tool_approvals": {"enabled"}, // 000091
}
-const expectedSQLiteMigrationVersion = 21
+const expectedSQLiteMigrationVersion = 22
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
diff --git a/internal/handler/deployment_capabilities.go b/internal/handler/deployment_capabilities.go
index 9c8d905a6..7d8afc46d 100644
--- a/internal/handler/deployment_capabilities.go
+++ b/internal/handler/deployment_capabilities.go
@@ -16,6 +16,7 @@ var DeploymentCapabilityKeys = []string{
"integrations.im",
"integrations.embed",
"integrations.api",
+ "integrations.mcpserver",
"settings.mcp",
"settings.websearch",
"settings.vectorstore",
@@ -43,6 +44,7 @@ type DeploymentFeatureAvailability struct {
IM bool
Embed bool
API bool
+ MCPServer bool
MCP bool
WebSearch bool
VectorStore bool
@@ -86,6 +88,7 @@ func BuildDeploymentCapabilities(
"integrations.im": supportedDeploymentCapability(available.IM),
"integrations.embed": supportedDeploymentCapability(available.Embed),
"integrations.api": supportedDeploymentCapability(available.API),
+ "integrations.mcpserver": supportedDeploymentCapability(available.MCPServer),
"settings.mcp": supportedDeploymentCapability(available.MCP),
"settings.websearch": supportedDeploymentCapability(available.WebSearch),
"settings.vectorstore": supportedDeploymentCapability(available.VectorStore),
diff --git a/internal/handler/mcp_endpoint.go b/internal/handler/mcp_endpoint.go
new file mode 100644
index 000000000..aea6f0786
--- /dev/null
+++ b/internal/handler/mcp_endpoint.go
@@ -0,0 +1,290 @@
+package handler
+
+import (
+ "errors"
+ "net/http"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
+ "github.com/gin-gonic/gin"
+)
+
+// MCPEndpointHandler manages the workspace's published MCP server endpoints.
+type MCPEndpointHandler struct {
+ svc interfaces.MCPEndpointService
+}
+
+// NewMCPEndpointHandler creates the MCP endpoint management handler.
+func NewMCPEndpointHandler(svc interfaces.MCPEndpointService) *MCPEndpointHandler {
+ return &MCPEndpointHandler{svc: svc}
+}
+
+type mcpEndpointRequest struct {
+ Name *string `json:"name"`
+ Description *string `json:"description"`
+ Enabled *bool `json:"enabled"`
+ KnowledgeBaseIDs *[]string `json:"knowledge_base_ids"`
+ Tools *[]string `json:"tools"`
+ DefaultAgentID *string `json:"default_agent_id"`
+ RateLimitPerMinute *int `json:"rate_limit_per_minute"`
+}
+
+func stringValue(p *string) string {
+ if p == nil {
+ return ""
+ }
+ return *p
+}
+
+// ListToolCatalog returns the tools an endpoint can expose, grouped.
+//
+// @Summary 获取 MCP 端点工具目录
+// @Description 返回工作空间 MCP 端点可勾选的工具清单、分组和默认勾选项
+// @Tags MCP端点
+// @Produce json
+// @Success 200 {object} map[string]interface{} "工具目录"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /mcp-endpoints/tools [get]
+func (h *MCPEndpointHandler) ListToolCatalog(c *gin.Context) {
+ groups := types.MCPEndpointToolGroups()
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "groups": groups,
+ "tools": types.MCPEndpointToolCatalog(),
+ "default_tools": types.DefaultMCPEndpointTools(),
+ },
+ })
+}
+
+// CreateMCPEndpoint creates an endpoint and returns it with the one-time token.
+//
+// @Summary 创建 MCP 端点
+// @Description 为当前工作空间发布一个 MCP 端点,响应中的 token 只返回一次
+// @Tags MCP端点
+// @Accept json
+// @Produce json
+// @Param request body object true "端点配置:name、description、enabled、knowledge_base_ids、tools 等"
+// @Success 201 {object} map[string]interface{} "创建的端点,含一次性 token"
+// @Failure 400 {object} map[string]interface{} "请求参数错误"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /mcp-endpoints [post]
+func (h *MCPEndpointHandler) CreateMCPEndpoint(c *gin.Context) {
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ var req mcpEndpointRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ enabled := true
+ if req.Enabled != nil {
+ enabled = *req.Enabled
+ }
+ tools := types.DefaultMCPEndpointTools()
+ if req.Tools != nil {
+ tools = *req.Tools
+ }
+ var kbIDs []string
+ if req.KnowledgeBaseIDs != nil {
+ kbIDs = *req.KnowledgeBaseIDs
+ }
+ rate := 0
+ if req.RateLimitPerMinute != nil {
+ rate = *req.RateLimitPerMinute
+ }
+ ep, token, err := h.svc.Create(c.Request.Context(), tenantID, &types.MCPEndpoint{
+ Name: stringValue(req.Name),
+ Description: stringValue(req.Description),
+ Enabled: enabled,
+ KnowledgeBaseIDs: types.StringArray(kbIDs),
+ Tools: types.StringArray(tools),
+ DefaultAgentID: stringValue(req.DefaultAgentID),
+ RateLimitPerMinute: rate,
+ })
+ if err != nil {
+ writeMCPEndpointMgmtError(c, err)
+ return
+ }
+ c.JSON(http.StatusCreated, gin.H{"success": true, "data": mcpEndpointResponse(ep, token)})
+}
+
+// ListMCPEndpoints lists the workspace endpoints without tokens.
+//
+// @Summary 获取 MCP 端点列表
+// @Tags MCP端点
+// @Produce json
+// @Success 200 {object} map[string]interface{} "端点列表"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /mcp-endpoints [get]
+func (h *MCPEndpointHandler) ListMCPEndpoints(c *gin.Context) {
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ rows, err := h.svc.List(c.Request.Context(), tenantID)
+ if err != nil {
+ writeMCPEndpointMgmtError(c, err)
+ return
+ }
+ out := make([]gin.H, 0, len(rows))
+ for _, ep := range rows {
+ out = append(out, mcpEndpointResponse(ep, ""))
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
+}
+
+// GetMCPEndpoint returns one endpoint.
+//
+// @Summary 获取 MCP 端点详情
+// @Tags MCP端点
+// @Produce json
+// @Param endpoint_id path string true "端点 ID"
+// @Success 200 {object} map[string]interface{} "端点详情"
+// @Failure 404 {object} map[string]interface{} "端点不存在"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /mcp-endpoints/{endpoint_id} [get]
+func (h *MCPEndpointHandler) GetMCPEndpoint(c *gin.Context) {
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ id := secutils.SanitizeForLog(c.Param("endpoint_id"))
+ ep, err := h.svc.Get(c.Request.Context(), tenantID, id)
+ if err != nil {
+ writeMCPEndpointMgmtError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": mcpEndpointResponse(ep, "")})
+}
+
+// UpdateMCPEndpoint applies a partial update; omitted fields are kept.
+//
+// @Summary 更新 MCP 端点
+// @Tags MCP端点
+// @Accept json
+// @Produce json
+// @Param endpoint_id path string true "端点 ID"
+// @Param request body object true "要更新的字段,未提供的字段保持不变"
+// @Success 200 {object} map[string]interface{} "更新后的端点"
+// @Failure 400 {object} map[string]interface{} "请求参数错误"
+// @Failure 404 {object} map[string]interface{} "端点不存在"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /mcp-endpoints/{endpoint_id} [put]
+func (h *MCPEndpointHandler) UpdateMCPEndpoint(c *gin.Context) {
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ id := secutils.SanitizeForLog(c.Param("endpoint_id"))
+ var req mcpEndpointRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ ep, err := h.svc.Update(c.Request.Context(), tenantID, id, interfaces.MCPEndpointUpdate{
+ Name: req.Name,
+ Description: req.Description,
+ Enabled: req.Enabled,
+ KnowledgeBaseIDs: req.KnowledgeBaseIDs,
+ Tools: req.Tools,
+ DefaultAgentID: req.DefaultAgentID,
+ RateLimitPerMinute: req.RateLimitPerMinute,
+ })
+ if err != nil {
+ writeMCPEndpointMgmtError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": mcpEndpointResponse(ep, "")})
+}
+
+// DeleteMCPEndpoint soft-deletes an endpoint; connected clients lose access.
+//
+// @Summary 删除 MCP 端点
+// @Tags MCP端点
+// @Produce json
+// @Param endpoint_id path string true "端点 ID"
+// @Success 200 {object} map[string]interface{} "删除成功"
+// @Failure 404 {object} map[string]interface{} "端点不存在"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /mcp-endpoints/{endpoint_id} [delete]
+func (h *MCPEndpointHandler) DeleteMCPEndpoint(c *gin.Context) {
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ id := secutils.SanitizeForLog(c.Param("endpoint_id"))
+ if err := h.svc.Delete(c.Request.Context(), tenantID, id); err != nil {
+ writeMCPEndpointMgmtError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// RotateMCPEndpointToken issues a fresh token and returns it once.
+//
+// @Summary 轮换 MCP 端点令牌
+// @Description 生成新令牌并立即作废旧令牌,响应中的 token 只返回一次
+// @Tags MCP端点
+// @Produce json
+// @Param endpoint_id path string true "端点 ID"
+// @Success 200 {object} map[string]interface{} "含新 token 的端点"
+// @Failure 404 {object} map[string]interface{} "端点不存在"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /mcp-endpoints/{endpoint_id}/rotate-token [post]
+func (h *MCPEndpointHandler) RotateMCPEndpointToken(c *gin.Context) {
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ id := secutils.SanitizeForLog(c.Param("endpoint_id"))
+ ep, token, err := h.svc.RotateToken(c.Request.Context(), tenantID, id)
+ if err != nil {
+ writeMCPEndpointMgmtError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": mcpEndpointResponse(ep, token)})
+}
+
+// MCPEndpointPath is the public path prefix the MCP server is mounted on.
+const MCPEndpointPath = "/mcp/"
+
+func mcpEndpointResponse(ep *types.MCPEndpoint, token string) gin.H {
+ row := gin.H{
+ "id": ep.ID,
+ "tenant_id": ep.TenantID,
+ "name": ep.Name,
+ "description": ep.Description,
+ "enabled": ep.Enabled,
+ "token_hint": ep.TokenHint,
+ "knowledge_base_ids": []string(ep.KnowledgeBaseIDs),
+ "tools": []string(ep.Tools),
+ "default_agent_id": ep.DefaultAgentID,
+ "rate_limit_per_minute": ep.RateLimitPerMinute,
+ "path": MCPEndpointPath + ep.ID,
+ "last_used_at": ep.LastUsedAt,
+ "created_at": ep.CreatedAt,
+ "updated_at": ep.UpdatedAt,
+ }
+ if strings.TrimSpace(token) != "" {
+ row["token"] = token
+ }
+ return row
+}
+
+func writeMCPEndpointMgmtError(c *gin.Context, err error) {
+ switch {
+ case errors.Is(err, service.ErrMCPEndpointNotFound):
+ c.JSON(http.StatusNotFound, gin.H{"error": "mcp endpoint not found"})
+ default:
+ var appErr *apperrors.AppError
+ if errors.As(err, &appErr) {
+ switch appErr.Code {
+ case apperrors.ErrNotFound:
+ c.JSON(http.StatusNotFound, gin.H{"error": appErr.Message})
+ return
+ case apperrors.ErrBadRequest, apperrors.ErrValidation:
+ c.JSON(http.StatusBadRequest, gin.H{"error": appErr.Message})
+ return
+ }
+ }
+ logger.Error(c.Request.Context(), "mcp endpoint management failed", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "operation failed"})
+ }
+}
diff --git a/internal/mcpserver/scope.go b/internal/mcpserver/scope.go
new file mode 100644
index 000000000..683f178ef
--- /dev/null
+++ b/internal/mcpserver/scope.go
@@ -0,0 +1,222 @@
+package mcpserver
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/application/access"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// allowedKnowledgeBases returns every knowledge base the endpoint may touch,
+// each one re-authorized for the calling principal through access.ResolveKB
+// so a stale or foreign ID in the allowlist is dropped rather than trusted.
+// An unrestricted endpoint sees the workspace's own knowledge bases.
+func (s *Server) allowedKnowledgeBases(ctx context.Context, ep *types.MCPEndpoint) ([]*types.KnowledgeBase, error) {
+ if !ep.RestrictsKnowledgeBases() {
+ return s.kbService.ListKnowledgeBases(ctx)
+ }
+ out := make([]*types.KnowledgeBase, 0, len(ep.KnowledgeBaseIDs))
+ for _, id := range ep.KnowledgeBaseIDs {
+ kb, err := s.authorizedKnowledgeBase(ctx, id, types.OrgRoleViewer)
+ if err != nil {
+ logger.Warnf(ctx, "[mcpserver] endpoint %s references unavailable knowledge base %s: %v",
+ ep.ID, id, err)
+ continue
+ }
+ out = append(out, kb)
+ }
+ return out, nil
+}
+
+// authorizedKnowledgeBase loads a knowledge base by ID and resolves the
+// caller's permission on it (ownership or organization share). The returned
+// error is access.ErrForbidden / ErrNotFound for authorization failures.
+func (s *Server) authorizedKnowledgeBase(
+ ctx context.Context, kbID string, required types.OrgMemberRole,
+) (*types.KnowledgeBase, error) {
+ kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, strings.TrimSpace(kbID))
+ if err != nil || kb == nil {
+ return nil, access.ErrNotFound
+ }
+ if _, err := s.resolveKB(ctx, kb, required); err != nil {
+ return nil, err
+ }
+ return kb, nil
+}
+
+func (s *Server) resolveKB(
+ ctx context.Context, kb *types.KnowledgeBase, required types.OrgMemberRole,
+) (*access.KBAccess, error) {
+ request := access.KBRequest{Caller: types.CallerFromContext(ctx)}
+ return access.ResolveKB(ctx, request, kb, required, s.kbShareService, nil)
+}
+
+// scopedKBContext authorizes one knowledge base at the required permission
+// and returns the context every document-level call must run under: it
+// carries the resolved grant (so access.RequireKBWrite sees an explicit
+// authorization instead of an implicit "same tenant") and switches the
+// execution tenant to the knowledge base owner, which is what makes shared
+// knowledge bases work. Their documents are stored under the owner tenant,
+// so listing, reading and writing them through the caller's tenant would
+// either find nothing or create rows under the wrong tenant.
+//
+// TenantInfo is swapped to the owner as well so model and storage settings
+// resolve against the workspace that holds the data, mirroring the service
+// layer's withKBWriteTenantInfo.
+func (s *Server) scopedKBContext(
+ ctx context.Context, kb *types.KnowledgeBase, required types.OrgMemberRole,
+) (context.Context, error) {
+ grant, err := s.resolveKB(ctx, kb, required)
+ if err != nil {
+ if errors.Is(err, access.ErrForbidden) || errors.Is(err, access.ErrUnauthorized) {
+ if required == types.OrgRoleViewer {
+ return ctx, fmt.Errorf("this endpoint is not allowed to read knowledge base %q", kb.ID)
+ }
+ return ctx, fmt.Errorf("this endpoint is not allowed to write to knowledge base %q", kb.ID)
+ }
+ return ctx, err
+ }
+ scoped := grant.Context(ctx)
+ caller := types.CallerFromContext(ctx)
+ if kb.TenantID != caller.TenantID && s.tenantService != nil {
+ owner, err := s.tenantService.GetTenantByID(ctx, kb.TenantID)
+ if err != nil || owner == nil {
+ return ctx, fmt.Errorf("the workspace owning knowledge base %q is unavailable", kb.ID)
+ }
+ scoped = context.WithValue(scoped, types.TenantInfoContextKey, owner)
+ }
+ return scoped, nil
+}
+
+// selectKnowledgeBases narrows the allowed set to the ones a caller named,
+// accepting either IDs or exact (case-insensitive) names. With no selector
+// every allowed knowledge base is returned.
+func (s *Server) selectKnowledgeBases(
+ ctx context.Context, ep *types.MCPEndpoint, requested []string,
+) ([]*types.KnowledgeBase, error) {
+ allowed, err := s.allowedKnowledgeBases(ctx, ep)
+ if err != nil {
+ return nil, err
+ }
+ if len(allowed) == 0 {
+ return nil, fmt.Errorf("no knowledge base is available on this endpoint")
+ }
+ cleaned := make([]string, 0, len(requested))
+ for _, r := range requested {
+ if r = strings.TrimSpace(r); r != "" {
+ cleaned = append(cleaned, r)
+ }
+ }
+ if len(cleaned) == 0 {
+ return allowed, nil
+ }
+ out := make([]*types.KnowledgeBase, 0, len(cleaned))
+ seen := map[string]struct{}{}
+ for _, sel := range cleaned {
+ kb := matchKnowledgeBase(allowed, sel)
+ if kb == nil {
+ return nil, fmt.Errorf("knowledge base %q was not found or is outside this endpoint's scope; "+
+ "call list_knowledge_bases to see what is available", sel)
+ }
+ if _, dup := seen[kb.ID]; dup {
+ continue
+ }
+ seen[kb.ID] = struct{}{}
+ out = append(out, kb)
+ }
+ return out, nil
+}
+
+func matchKnowledgeBase(kbs []*types.KnowledgeBase, selector string) *types.KnowledgeBase {
+ for _, kb := range kbs {
+ if kb.ID == selector {
+ return kb
+ }
+ }
+ for _, kb := range kbs {
+ if strings.EqualFold(strings.TrimSpace(kb.Name), selector) {
+ return kb
+ }
+ }
+ return nil
+}
+
+// searchTargetsFor builds whole-knowledge-base search targets. TenantID is
+// carried per target because shared knowledge bases index under their owner.
+func searchTargetsFor(kbs []*types.KnowledgeBase) types.SearchTargets {
+ targets := make(types.SearchTargets, 0, len(kbs))
+ for _, kb := range kbs {
+ targets = append(targets, &types.SearchTarget{
+ Type: types.SearchTargetTypeKnowledgeBase,
+ KnowledgeBaseID: kb.ID,
+ TenantID: kb.TenantID,
+ })
+ }
+ return targets
+}
+
+func knowledgeBaseIDs(kbs []*types.KnowledgeBase) []string {
+ ids := make([]string, 0, len(kbs))
+ for _, kb := range kbs {
+ ids = append(ids, kb.ID)
+ }
+ return ids
+}
+
+// retrievableKnowledgeBases keeps knowledge bases that have a vector or
+// keyword index, i.e. the ones the search tools can actually query.
+func retrievableKnowledgeBases(kbs []*types.KnowledgeBase) []*types.KnowledgeBase {
+ out := make([]*types.KnowledgeBase, 0, len(kbs))
+ for _, kb := range kbs {
+ if kb.IsVectorEnabled() || kb.IsKeywordEnabled() {
+ out = append(out, kb)
+ }
+ }
+ return out
+}
+
+// wikiKnowledgeBases keeps knowledge bases with a generated wiki.
+func wikiKnowledgeBases(kbs []*types.KnowledgeBase) []*types.KnowledgeBase {
+ out := make([]*types.KnowledgeBase, 0, len(kbs))
+ for _, kb := range kbs {
+ if kb.IsWikiEnabled() {
+ out = append(out, kb)
+ }
+ }
+ return out
+}
+
+func wikiScopesFor(kbs []*types.KnowledgeBase) []tools.WikiScope {
+ return tools.NewWikiScopesFromKBIDs(knowledgeBaseIDs(kbs))
+}
+
+// knowledgeInScope loads a document and confirms it belongs to a knowledge
+// base the endpoint may touch. The lookup is tenant-agnostic because a shared
+// knowledge base's documents live under the owner tenant; the document must
+// then match an allowed knowledge base and that knowledge base's tenant.
+func (s *Server) knowledgeInScope(
+ ctx context.Context, ep *types.MCPEndpoint, knowledgeID string,
+) (*types.Knowledge, *types.KnowledgeBase, error) {
+ knowledgeID = strings.TrimSpace(knowledgeID)
+ if knowledgeID == "" {
+ return nil, nil, fmt.Errorf("knowledge_id is required")
+ }
+ k, err := s.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
+ if err != nil || k == nil {
+ return nil, nil, fmt.Errorf("document %q was not found", knowledgeID)
+ }
+ allowed, err := s.allowedKnowledgeBases(ctx, ep)
+ if err != nil {
+ return nil, nil, err
+ }
+ kb := matchKnowledgeBase(allowed, k.KnowledgeBaseID)
+ if kb == nil || kb.TenantID != k.TenantID {
+ return nil, nil, fmt.Errorf("document %q is outside this endpoint's scope", knowledgeID)
+ }
+ return k, kb, nil
+}
diff --git a/internal/mcpserver/scope_test.go b/internal/mcpserver/scope_test.go
new file mode 100644
index 000000000..cba945049
--- /dev/null
+++ b/internal/mcpserver/scope_test.go
@@ -0,0 +1,281 @@
+package mcpserver
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/access"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+type stubKBService struct {
+ interfaces.KnowledgeBaseService
+ kbs map[string]*types.KnowledgeBase
+}
+
+func (s *stubKBService) GetKnowledgeBaseByIDOnly(_ context.Context, id string) (*types.KnowledgeBase, error) {
+ kb, ok := s.kbs[id]
+ if !ok {
+ return nil, errors.New("not found")
+ }
+ return kb, nil
+}
+
+func (s *stubKBService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
+ tenantID := types.MustTenantIDFromContext(ctx)
+ out := []*types.KnowledgeBase{}
+ for _, kb := range s.kbs {
+ if kb.TenantID == tenantID {
+ out = append(out, kb)
+ }
+ }
+ return out, nil
+}
+
+type stubAgentService struct {
+ interfaces.CustomAgentService
+ agents map[string]*types.CustomAgent
+}
+
+func (s *stubAgentService) GetAgentByID(_ context.Context, id string) (*types.CustomAgent, error) {
+ agent, ok := s.agents[id]
+ if !ok {
+ return nil, errors.New("not found")
+ }
+ return agent, nil
+}
+
+func mcpCallContext(tenantID uint64, ep *types.MCPEndpoint) context.Context {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, tenantID)
+ ctx = context.WithValue(ctx, types.MCPEndpointContextKey, ep)
+ ctx = types.WithTenantAPIKeyScope(ctx, types.MCPEndpointScope(ep))
+ return types.WithCaller(ctx, types.Caller{TenantID: tenantID, UserID: "mcp-" + ep.ID, Role: types.TenantRoleViewer})
+}
+
+func newScopeTestServer(kbs ...*types.KnowledgeBase) *Server {
+ stub := &stubKBService{kbs: map[string]*types.KnowledgeBase{}}
+ for _, kb := range kbs {
+ stub.kbs[kb.ID] = kb
+ }
+ return &Server{kbService: stub}
+}
+
+func TestAllowedKnowledgeBasesDropsForeignIDs(t *testing.T) {
+ srv := newScopeTestServer(
+ &types.KnowledgeBase{ID: "kb-own", TenantID: 1, Name: "Own"},
+ &types.KnowledgeBase{ID: "kb-foreign", TenantID: 2, Name: "Foreign"},
+ )
+ ep := &types.MCPEndpoint{
+ ID: "ep", TenantID: 1, KnowledgeBaseIDs: types.StringArray{"kb-own", "kb-foreign", "kb-gone"},
+ }
+ kbs, err := srv.allowedKnowledgeBases(mcpCallContext(1, ep), ep)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(kbs) != 1 || kbs[0].ID != "kb-own" {
+ t.Fatalf("expected only the owned knowledge base, got %v", knowledgeBaseIDs(kbs))
+ }
+}
+
+func TestSelectKnowledgeBasesMatchesIDOrName(t *testing.T) {
+ srv := newScopeTestServer(
+ &types.KnowledgeBase{ID: "kb-1", TenantID: 1, Name: "Product Docs"},
+ &types.KnowledgeBase{ID: "kb-2", TenantID: 1, Name: "Support"},
+ &types.KnowledgeBase{ID: "kb-3", TenantID: 2, Name: "Other tenant"},
+ )
+ ep := &types.MCPEndpoint{ID: "ep", TenantID: 1}
+ ctx := mcpCallContext(1, ep)
+
+ all, err := srv.selectKnowledgeBases(ctx, ep, nil)
+ if err != nil || len(all) != 2 {
+ t.Fatalf("unrestricted endpoint must see its workspace only: %v %v", knowledgeBaseIDs(all), err)
+ }
+ picked, err := srv.selectKnowledgeBases(ctx, ep, []string{"product docs", "kb-2", "kb-2"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := knowledgeBaseIDs(picked); len(got) != 2 || got[0] != "kb-1" || got[1] != "kb-2" {
+ t.Fatalf("name/id selection = %v", got)
+ }
+ _, err = srv.selectKnowledgeBases(ctx, ep, []string{"kb-3"})
+ if err == nil || !strings.Contains(err.Error(), "outside") {
+ t.Fatalf("foreign knowledge base must be rejected, got %v", err)
+ }
+}
+
+type stubKBShareService struct {
+ interfaces.KBShareService
+ shared map[string]types.OrgMemberRole // kb id -> permission granted to any caller
+}
+
+func (s *stubKBShareService) CheckTenantKBPermission(
+ _ context.Context, kbID string, _ uint64, _ types.TenantRole,
+) (types.OrgMemberRole, bool, error) {
+ perm, ok := s.shared[kbID]
+ return perm, ok, nil
+}
+
+type stubTenantService struct {
+ interfaces.TenantService
+ tenants map[uint64]*types.Tenant
+}
+
+func (s *stubTenantService) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) {
+ t, ok := s.tenants[id]
+ if !ok {
+ return nil, errors.New("not found")
+ }
+ return t, nil
+}
+
+type stubKnowledgeService struct {
+ interfaces.KnowledgeService
+ docs map[string]*types.Knowledge
+}
+
+func (s *stubKnowledgeService) GetKnowledgeByIDOnly(_ context.Context, id string) (*types.Knowledge, error) {
+ k, ok := s.docs[id]
+ if !ok {
+ return nil, errors.New("not found")
+ }
+ return k, nil
+}
+
+func TestScopedKBContextEnablesWritesOnlyForAuthorizedKnowledgeBases(t *testing.T) {
+ own := &types.KnowledgeBase{ID: "kb-own", TenantID: 1}
+ foreign := &types.KnowledgeBase{ID: "kb-foreign", TenantID: 2}
+ srv := newScopeTestServer(own, foreign)
+ ep := &types.MCPEndpoint{ID: "ep", TenantID: 1, Tools: types.StringArray{types.MCPEndpointToolAddDocument}}
+ ctx := mcpCallContext(1, ep)
+
+ if err := access.RequireKBWrite(ctx, own); err == nil {
+ t.Fatal("no grant must exist before scopedKBContext runs")
+ }
+ scoped, err := srv.scopedKBContext(ctx, own, types.OrgRoleEditor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := access.RequireKBWrite(scoped, own); err != nil {
+ t.Fatalf("owned knowledge base must be writable after grant: %v", err)
+ }
+ if got := types.MustTenantIDFromContext(scoped); got != 1 {
+ t.Fatalf("execution tenant = %d, want owner 1", got)
+ }
+ if _, err := srv.scopedKBContext(ctx, foreign, types.OrgRoleEditor); err == nil {
+ t.Fatal("foreign knowledge base must not receive a write grant")
+ }
+
+ readOnly := &types.MCPEndpoint{
+ ID: "ep2", TenantID: 1, Tools: types.StringArray{types.MCPEndpointToolSearchKnowledge},
+ }
+ roScoped, err := srv.scopedKBContext(mcpCallContext(1, readOnly), own, types.OrgRoleEditor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := access.RequireKBWrite(roScoped, own); err == nil {
+ t.Fatal("an endpoint without ingest tools must lack the ingest capability and be refused")
+ }
+}
+
+func TestSharedKnowledgeBaseRunsUnderOwnerTenant(t *testing.T) {
+ shared := &types.KnowledgeBase{ID: "kb-shared", TenantID: 2, Name: "Shared"}
+ srv := newScopeTestServer(shared)
+ srv.kbShareService = &stubKBShareService{shared: map[string]types.OrgMemberRole{"kb-shared": types.OrgRoleEditor}}
+ srv.tenantService = &stubTenantService{tenants: map[uint64]*types.Tenant{2: {ID: 2, Name: "Owner"}}}
+ srv.knowledgeService = &stubKnowledgeService{docs: map[string]*types.Knowledge{
+ "doc-shared": {ID: "doc-shared", TenantID: 2, KnowledgeBaseID: "kb-shared"},
+ "doc-spoof": {ID: "doc-spoof", TenantID: 1, KnowledgeBaseID: "kb-shared"},
+ }}
+ ep := &types.MCPEndpoint{
+ ID: "ep", TenantID: 1, KnowledgeBaseIDs: types.StringArray{"kb-shared"},
+ Tools: types.StringArray{types.MCPEndpointToolUpdateDocument},
+ }
+ ctx := context.WithValue(mcpCallContext(1, ep), types.TenantInfoContextKey, &types.Tenant{ID: 1, Name: "Caller"})
+
+ // The shared knowledge base is visible through the organization share.
+ kbs, err := srv.allowedKnowledgeBases(ctx, ep)
+ if err != nil || len(kbs) != 1 {
+ t.Fatalf("shared knowledge base must be in scope: %v %v", knowledgeBaseIDs(kbs), err)
+ }
+
+ // Its document resolves even though it lives under tenant 2 ...
+ k, kb, err := srv.knowledgeInScope(ctx, ep, "doc-shared")
+ if err != nil || k.ID != "doc-shared" || kb.ID != "kb-shared" {
+ t.Fatalf("shared document must be in scope: %v %v %v", k, kb, err)
+ }
+ // ... but a document whose tenant does not match its knowledge base is not.
+ if _, _, err := srv.knowledgeInScope(ctx, ep, "doc-spoof"); err == nil {
+ t.Fatal("document with mismatched tenant must be rejected")
+ }
+
+ // Writes run under the owner tenant with an editor grant and owner TenantInfo.
+ scoped, err := srv.scopedKBContext(ctx, kb, types.OrgRoleEditor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := types.MustTenantIDFromContext(scoped); got != 2 {
+ t.Fatalf("execution tenant = %d, want owner 2", got)
+ }
+ if info, ok := types.TenantInfoFromContext(scoped); !ok || info.ID != 2 {
+ t.Fatalf("tenant info must be swapped to the owner, got %+v", info)
+ }
+ if err := access.RequireKBWrite(scoped, kb); err != nil {
+ t.Fatalf("editor share must allow writes: %v", err)
+ }
+ if caller := types.CallerFromContext(scoped); caller.TenantID != 1 {
+ t.Fatalf("caller must stay the endpoint tenant, got %+v", caller)
+ }
+
+ // A viewer share must not mint a write grant.
+ srv.kbShareService = &stubKBShareService{shared: map[string]types.OrgMemberRole{"kb-shared": types.OrgRoleViewer}}
+ if _, err := srv.scopedKBContext(ctx, kb, types.OrgRoleEditor); err == nil {
+ t.Fatal("viewer share must not allow writes")
+ }
+ if _, err := srv.scopedKBContext(ctx, kb, types.OrgRoleViewer); err != nil {
+ t.Fatalf("viewer share must allow reads: %v", err)
+ }
+}
+
+func TestResolveAskAgentUsesEndpointAgentOnly(t *testing.T) {
+ agents := &stubAgentService{agents: map[string]*types.CustomAgent{
+ types.BuiltinQuickAnswerID: {ID: types.BuiltinQuickAnswerID, TenantID: 1, IsBuiltin: true},
+ types.BuiltinWikiFixerID: {ID: types.BuiltinWikiFixerID, TenantID: 1, IsBuiltin: true},
+ "agent-own": {ID: "agent-own", TenantID: 1},
+ "agent-foreign": {ID: "agent-foreign", TenantID: 2},
+ }}
+ srv := &Server{agentService: agents}
+
+ got, err := srv.resolveAskAgent(context.Background(), &types.MCPEndpoint{ID: "ep", TenantID: 1})
+ if err != nil || got.ID != types.BuiltinQuickAnswerID {
+ t.Fatalf("empty default must fall back to quick answer: %v %v", got, err)
+ }
+ got, err = srv.resolveAskAgent(context.Background(),
+ &types.MCPEndpoint{ID: "ep", TenantID: 1, DefaultAgentID: "agent-own"})
+ if err != nil || got.ID != "agent-own" {
+ t.Fatalf("configured tenant agent must be used: %v %v", got, err)
+ }
+ for _, bad := range []string{types.BuiltinWikiFixerID, "agent-foreign", "agent-missing"} {
+ _, err := srv.resolveAskAgent(context.Background(),
+ &types.MCPEndpoint{ID: "ep", TenantID: 1, DefaultAgentID: bad})
+ if err == nil {
+ t.Fatalf("agent %q must be refused", bad)
+ }
+ }
+}
+
+func TestAskToolHasNoAgentParameter(t *testing.T) {
+ tool := askTool()
+ if _, ok := tool.InputSchema.Properties["agent_id"]; ok {
+ t.Fatal("ask must not let clients pick an agent")
+ }
+ if tool.Annotations.ReadOnlyHint != nil && *tool.Annotations.ReadOnlyHint {
+ t.Fatal("ask must not advertise itself as read-only")
+ }
+ add := addDocumentTool()
+ if add.Annotations.DestructiveHint == nil || !*add.Annotations.DestructiveHint {
+ t.Fatal("add_document must advertise a mutation")
+ }
+}
diff --git a/internal/mcpserver/server.go b/internal/mcpserver/server.go
new file mode 100644
index 000000000..04165f28b
--- /dev/null
+++ b/internal/mcpserver/server.go
@@ -0,0 +1,235 @@
+// Package mcpserver hosts WeKnora's own MCP server surface: the Streamable
+// HTTP endpoint that external MCP clients (Claude Desktop, Cursor, VS Code
+// Copilot, ...) connect to. Every request is authenticated by
+// middleware.MCPEndpointAuth against a workspace MCPEndpoint row, and the
+// endpoint's tool allowlist and knowledge-base scope decide what the client
+// can see and call.
+//
+// A single mcp-go server instance is registered with the full tool catalog;
+// per-endpoint visibility is applied through a tool filter (tools/list) and a
+// handler middleware (tools/call), both keyed off the endpoint on the request
+// context. The transport runs stateless so any replica can answer any call.
+package mcpserver
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/config"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/ratelimit"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/mark3labs/mcp-go/mcp"
+ "github.com/mark3labs/mcp-go/server"
+ "github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
+)
+
+const (
+ serverName = "weknora"
+ serverVersion = "1.0.0"
+
+ rateLimitKeyPrefix = "mcp:endpoint:ratelimit:"
+ lastUsedTouchEvery = time.Minute
+)
+
+var errNoEndpoint = errors.New("mcp endpoint missing from request context")
+
+// Server wires the tool catalog onto an mcp-go server and exposes it as an
+// http.Handler.
+type Server struct {
+ kbService interfaces.KnowledgeBaseService
+ knowledgeService interfaces.KnowledgeService
+ chunkService interfaces.ChunkService
+ wikiService interfaces.WikiPageService
+ sessionService interfaces.SessionService
+ messageService interfaces.MessageService
+ agentService interfaces.CustomAgentService
+ kbShareService interfaces.KBShareService
+ tenantService interfaces.TenantService
+ endpointRepo interfaces.MCPEndpointRepository
+ db *gorm.DB
+ cfg *config.Config
+
+ limiter *ratelimit.Limiter
+ lastTouch sync.Map // endpoint id -> time.Time of the last last_used_at write
+
+ mcp *server.MCPServer
+ handler http.Handler
+}
+
+// NewServer builds the MCP server and its Streamable HTTP transport.
+func NewServer(
+ kbService interfaces.KnowledgeBaseService,
+ knowledgeService interfaces.KnowledgeService,
+ chunkService interfaces.ChunkService,
+ wikiService interfaces.WikiPageService,
+ sessionService interfaces.SessionService,
+ messageService interfaces.MessageService,
+ agentService interfaces.CustomAgentService,
+ kbShareService interfaces.KBShareService,
+ tenantService interfaces.TenantService,
+ endpointRepo interfaces.MCPEndpointRepository,
+ db *gorm.DB,
+ cfg *config.Config,
+ redisClient *redis.Client,
+) *Server {
+ s := &Server{
+ kbService: kbService,
+ knowledgeService: knowledgeService,
+ chunkService: chunkService,
+ wikiService: wikiService,
+ sessionService: sessionService,
+ messageService: messageService,
+ agentService: agentService,
+ kbShareService: kbShareService,
+ tenantService: tenantService,
+ endpointRepo: endpointRepo,
+ db: db,
+ cfg: cfg,
+ limiter: ratelimit.New(redisClient, rateLimitKeyPrefix, time.Minute, ""),
+ }
+ // The local fallback map only grows without periodic eviction; the server
+ // lives for the whole process so the cleanup goroutine never stops.
+ go s.limiter.StartCleanup(make(chan struct{}))
+ s.mcp = server.NewMCPServer(
+ serverName,
+ serverVersion,
+ server.WithToolCapabilities(false),
+ server.WithRecovery(),
+ server.WithToolFilter(s.filterTools),
+ server.WithToolHandlerMiddleware(s.guardTool),
+ server.WithInstructions(serverInstructions),
+ )
+ s.mcp.AddTools(s.toolCatalog()...)
+ s.handler = server.NewStreamableHTTPServer(
+ s.mcp,
+ server.WithStateLess(true),
+ )
+ return s
+}
+
+// Handler returns the http.Handler to mount under /mcp/:endpoint_id. The
+// caller must run MCPEndpointAuth first; the handler trusts the context.
+func (s *Server) Handler() http.Handler {
+ return s.handler
+}
+
+const serverInstructions = "WeKnora knowledge workspace. Start with list_knowledge_bases to see what is in scope, " +
+ "then use search_knowledge for semantic questions, grep_chunks for exact keywords, read_document to read " +
+ "a whole document, and ask to get a synthesized answer with citations. Wiki tools browse the generated " +
+ "wiki when a knowledge base has one. Write tools (add/update/delete_document) exist only on endpoints " +
+ "that enabled them."
+
+// endpointFromContext returns the endpoint authenticated for this call.
+func endpointFromContext(ctx context.Context) (*types.MCPEndpoint, error) {
+ ep, ok := ctx.Value(types.MCPEndpointContextKey).(*types.MCPEndpoint)
+ if !ok || ep == nil {
+ return nil, errNoEndpoint
+ }
+ return ep, nil
+}
+
+// filterTools hides catalog entries the endpoint did not enable.
+func (s *Server) filterTools(ctx context.Context, all []mcp.Tool) []mcp.Tool {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return nil
+ }
+ out := make([]mcp.Tool, 0, len(all))
+ for _, t := range all {
+ if ep.HasTool(t.Name) {
+ out = append(out, t)
+ }
+ }
+ return out
+}
+
+// guardTool enforces the allowlist and rate limit on every tools/call, so a
+// client cannot invoke a hidden tool by name.
+func (s *Server) guardTool(next server.ToolHandlerFunc) server.ToolHandlerFunc {
+ return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ if !ep.HasTool(req.Params.Name) {
+ return mcp.NewToolResultErrorf("tool %q is not enabled on this endpoint", req.Params.Name), nil
+ }
+ if !s.limiter.Allow(ctx, ep.ID, ep.RateLimitPerMinute) {
+ return mcp.NewToolResultError("rate limit exceeded for this endpoint, retry shortly"), nil
+ }
+ s.touchLastUsed(ctx, ep.ID)
+ return next(ctx, req)
+ }
+}
+
+// touchLastUsed records activity at most once a minute per endpoint.
+func (s *Server) touchLastUsed(ctx context.Context, endpointID string) {
+ if s.endpointRepo == nil {
+ return
+ }
+ now := time.Now()
+ if prev, ok := s.lastTouch.Load(endpointID); ok {
+ if last, ok := prev.(time.Time); ok && now.Sub(last) < lastUsedTouchEvery {
+ return
+ }
+ }
+ s.lastTouch.Store(endpointID, now)
+ go func() {
+ bg, cancel := context.WithTimeout(logger.CloneContext(ctx), 5*time.Second)
+ defer cancel()
+ if err := s.endpointRepo.TouchLastUsed(bg, endpointID); err != nil {
+ logger.Warnf(bg, "[mcpserver] touch last_used failed for %s: %v", endpointID, err)
+ }
+ }()
+}
+
+// toolCatalog lists every tool with its handler. Order matches the settings
+// catalog so tools/list is stable.
+func (s *Server) toolCatalog() []server.ServerTool {
+ return []server.ServerTool{
+ {Tool: listKnowledgeBasesTool(), Handler: s.handleListKnowledgeBases},
+ {Tool: searchKnowledgeTool(), Handler: s.handleSearchKnowledge},
+ {Tool: grepChunksTool(), Handler: s.handleGrepChunks},
+ {Tool: listDocumentsTool(), Handler: s.handleListDocuments},
+ {Tool: readDocumentTool(), Handler: s.handleReadDocument},
+ {Tool: askTool(), Handler: s.handleAsk},
+ {Tool: wikiSearchTool(), Handler: s.handleWikiSearch},
+ {Tool: wikiReadPageTool(), Handler: s.handleWikiReadPage},
+ {Tool: wikiIndexTool(), Handler: s.handleWikiIndex},
+ {Tool: addDocumentTool(), Handler: s.handleAddDocument},
+ {Tool: updateDocumentTool(), Handler: s.handleUpdateDocument},
+ {Tool: deleteDocumentTool(), Handler: s.handleDeleteDocument},
+ }
+}
+
+// toolResultFromAgentTool converts an agent tool result into an MCP result.
+// Agent tools already format their Output for a model reader, so the text
+// is passed through; Data is attached as structured content when present.
+func toolResultFromAgentTool(res *types.ToolResult, err error) *mcp.CallToolResult {
+ if err != nil && (res == nil || res.Error == "") {
+ return mcp.NewToolResultError(err.Error())
+ }
+ if res == nil {
+ return mcp.NewToolResultError("tool returned no result")
+ }
+ if !res.Success {
+ msg := res.Error
+ if msg == "" {
+ msg = res.Output
+ }
+ if msg == "" {
+ msg = "tool failed"
+ }
+ return mcp.NewToolResultError(msg)
+ }
+ if len(res.Data) > 0 {
+ return mcp.NewToolResultStructured(res.Data, res.Output)
+ }
+ return mcp.NewToolResultText(res.Output)
+}
diff --git a/internal/mcpserver/server_test.go b/internal/mcpserver/server_test.go
new file mode 100644
index 000000000..b4cdcabee
--- /dev/null
+++ b/internal/mcpserver/server_test.go
@@ -0,0 +1,205 @@
+package mcpserver
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+// recordingEndpointRepo captures last_used touches so the guard's background
+// write can be asserted (and never dereferences a nil repository).
+type recordingEndpointRepo struct {
+ interfaces.MCPEndpointRepository
+ touched chan string
+}
+
+func (r *recordingEndpointRepo) TouchLastUsed(_ context.Context, id string) error {
+ select {
+ case r.touched <- id:
+ default:
+ }
+ return nil
+}
+
+// newTestEngine mounts the MCP server behind a middleware that injects the
+// given endpoint straight onto the request context, standing in for
+// middleware.MCPEndpointAuth so the transport, tool filter and call guard
+// can be exercised without a database.
+func newTestEngine(t *testing.T, ep *types.MCPEndpoint) *gin.Engine {
+ engine, _ := newTestEngineWithRepo(t, ep)
+ return engine
+}
+
+func newTestEngineWithRepo(t *testing.T, ep *types.MCPEndpoint) (*gin.Engine, *recordingEndpointRepo) {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ repo := &recordingEndpointRepo{touched: make(chan string, 8)}
+ srv := NewServer(nil, nil, nil, nil, nil, nil, nil, nil, nil, repo, nil, nil, nil)
+ r := gin.New()
+ inject := func(c *gin.Context) {
+ if ep != nil {
+ ctx := context.WithValue(c.Request.Context(), types.MCPEndpointContextKey, ep)
+ ctx = context.WithValue(ctx, types.TenantIDContextKey, ep.TenantID)
+ c.Request = c.Request.WithContext(ctx)
+ }
+ c.Next()
+ }
+ r.POST("/mcp/:endpoint_id", inject, gin.WrapH(srv.Handler()))
+ return r, repo
+}
+
+func rpc(t *testing.T, r *gin.Engine, method string, params any) map[string]any {
+ t.Helper()
+ body, _ := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": method,
+ "params": params,
+ })
+ req := httptest.NewRequest(http.MethodPost, "/mcp/ep-1", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s: status %d body %s", method, w.Code, w.Body.String())
+ }
+ raw := w.Body.String()
+ // Streamable HTTP may answer as SSE; unwrap the data line if so.
+ if strings.HasPrefix(strings.TrimSpace(raw), "event:") || strings.HasPrefix(strings.TrimSpace(raw), "data:") {
+ for _, line := range strings.Split(raw, "\n") {
+ if strings.HasPrefix(line, "data:") {
+ raw = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
+ break
+ }
+ }
+ }
+ var out map[string]any
+ if err := json.Unmarshal([]byte(raw), &out); err != nil {
+ t.Fatalf("%s: bad json %q: %v", method, raw, err)
+ }
+ return out
+}
+
+func toolNames(t *testing.T, resp map[string]any) []string {
+ t.Helper()
+ result, _ := resp["result"].(map[string]any)
+ tools, _ := result["tools"].([]any)
+ names := make([]string, 0, len(tools))
+ for _, tl := range tools {
+ m, _ := tl.(map[string]any)
+ names = append(names, m["name"].(string))
+ }
+ return names
+}
+
+func TestToolsListIsFilteredByEndpoint(t *testing.T) {
+ ep := &types.MCPEndpoint{
+ ID: "ep-1", TenantID: 1, Enabled: true, RateLimitPerMinute: 100,
+ Tools: types.StringArray{types.MCPEndpointToolListKnowledgeBases, types.MCPEndpointToolAsk},
+ }
+ r := newTestEngine(t, ep)
+ names := toolNames(t, rpc(t, r, "tools/list", map[string]any{}))
+ sort.Strings(names)
+ if len(names) != 2 || names[0] != types.MCPEndpointToolAsk || names[1] != types.MCPEndpointToolListKnowledgeBases {
+ t.Fatalf("filtered tools = %v", names)
+ }
+}
+
+func TestToolsListEmptyWithoutEndpoint(t *testing.T) {
+ r := newTestEngine(t, nil)
+ if names := toolNames(t, rpc(t, r, "tools/list", map[string]any{})); len(names) != 0 {
+ t.Fatalf("expected no tools without an endpoint, got %v", names)
+ }
+}
+
+func TestCatalogMatchesSettingsCatalog(t *testing.T) {
+ all := types.StringArray{}
+ for _, def := range types.MCPEndpointToolCatalog() {
+ all = append(all, def.Name)
+ }
+ ep := &types.MCPEndpoint{ID: "ep-1", TenantID: 1, Enabled: true, Tools: all}
+ r := newTestEngine(t, ep)
+ names := toolNames(t, rpc(t, r, "tools/list", map[string]any{}))
+ if len(names) != len(all) {
+ t.Fatalf("server exposes %d tools, catalog has %d: %v", len(names), len(all), names)
+ }
+ // tools/list is sorted by name; compare as sets.
+ want := append([]string(nil), all...)
+ sort.Strings(want)
+ sort.Strings(names)
+ for i := range want {
+ if names[i] != want[i] {
+ t.Fatalf("tool mismatch at %d: %q vs %q", i, names[i], want[i])
+ }
+ }
+}
+
+func TestCallHiddenToolIsRefused(t *testing.T) {
+ ep := &types.MCPEndpoint{
+ ID: "ep-1", TenantID: 1, Enabled: true, RateLimitPerMinute: 100,
+ Tools: types.StringArray{types.MCPEndpointToolListKnowledgeBases},
+ }
+ r := newTestEngine(t, ep)
+ resp := rpc(t, r, "tools/call", map[string]any{
+ "name": types.MCPEndpointToolDeleteDocument,
+ "arguments": map[string]any{"knowledge_id": "k-1"},
+ })
+ result, _ := resp["result"].(map[string]any)
+ if isErr, _ := result["isError"].(bool); !isErr {
+ t.Fatalf("expected tool error, got %v", resp)
+ }
+ content, _ := result["content"].([]any)
+ first, _ := content[0].(map[string]any)
+ if !strings.Contains(first["text"].(string), "not enabled") {
+ t.Fatalf("unexpected error text: %v", first["text"])
+ }
+}
+
+func TestRateLimitPerEndpoint(t *testing.T) {
+ ep := &types.MCPEndpoint{
+ ID: "ep-1", TenantID: 1, Enabled: true, RateLimitPerMinute: 1,
+ Tools: types.StringArray{types.MCPEndpointToolReadDocument},
+ }
+ r, repo := newTestEngineWithRepo(t, ep)
+ call := func() string {
+ resp := rpc(t, r, "tools/call", map[string]any{
+ "name": types.MCPEndpointToolReadDocument,
+ "arguments": map[string]any{},
+ })
+ result, _ := resp["result"].(map[string]any)
+ content, _ := result["content"].([]any)
+ first, _ := content[0].(map[string]any)
+ return first["text"].(string)
+ }
+ // First call passes the guard and fails inside the handler on validation.
+ if text := call(); !strings.Contains(text, "knowledge_id is required") {
+ t.Fatalf("first call: %q", text)
+ }
+ if text := call(); !strings.Contains(text, "rate limit") {
+ t.Fatalf("second call should be rate limited: %q", text)
+ }
+ select {
+ case id := <-repo.touched:
+ if id != "ep-1" {
+ t.Fatalf("touched endpoint = %q", id)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("expected last_used_at to be touched after a guarded call")
+ }
+}
+
+func TestTouchLastUsedToleratesMissingRepository(_ *testing.T) {
+ srv := &Server{}
+ srv.touchLastUsed(context.Background(), "ep-1") // must not panic
+}
diff --git a/internal/mcpserver/tools_ask.go b/internal/mcpserver/tools_ask.go
new file mode 100644
index 000000000..4bc7f36cf
--- /dev/null
+++ b/internal/mcpserver/tools_ask.go
@@ -0,0 +1,429 @@
+package mcpserver
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/event"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/google/uuid"
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+const (
+ askTimeout = 4 * time.Minute
+ askCompleteWaitTimeout = 15 * time.Second
+ askSessionTitleMaxLen = 60
+ askChannel = "mcp"
+)
+
+func askTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolAsk,
+ mcp.WithDescription("Ask the workspace a question and get a synthesized answer with citations. "+
+ "WeKnora retrieves from the knowledge bases in scope and runs the agent configured on this "+
+ "endpoint. Pass the returned session_id on follow-up questions to keep the conversation going. "+
+ "This can take up to a few minutes for agentic runs; prefer search_knowledge when you only need "+
+ "raw passages."),
+ mcp.WithString("question", mcp.Required(), mcp.Description("The question to answer")),
+ mcp.WithString("session_id",
+ mcp.Description("Session id returned by a previous ask call, to continue that conversation")),
+ mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
+ mcp.Description("Optional knowledge base ids or names to retrieve from; defaults to the "+
+ "endpoint scope or the agent's own configuration")),
+ // Not read-only: it creates a session and messages, and the configured
+ // agent may run its own tools. Clients must not auto-approve it.
+ mcp.WithReadOnlyHintAnnotation(false),
+ )
+}
+
+type askReference struct {
+ KnowledgeID string `json:"knowledge_id"`
+ KnowledgeTitle string `json:"knowledge_title,omitempty"`
+ ChunkID string `json:"chunk_id"`
+ Score float64 `json:"score,omitempty"`
+ Excerpt string `json:"excerpt"`
+}
+
+func (s *Server) handleAsk(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ question, err := req.RequireString("question")
+ if err != nil || strings.TrimSpace(question) == "" {
+ return mcp.NewToolResultError("question is required"), nil
+ }
+ question = strings.TrimSpace(question)
+
+ agent, err := s.resolveAskAgent(ctx, ep)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ kbIDs, err := s.resolveAskKnowledgeBases(ctx, ep, agent, req.GetStringSlice("knowledge_base_ids", nil))
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ session, err := s.resolveAskSession(ctx, ep, req.GetString("session_id", ""), question)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+
+ answer, refs, err := s.runQA(ctx, session, agent, question, kbIDs)
+ if err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to answer", err), nil
+ }
+ structured := map[string]any{
+ "answer": answer,
+ "session_id": session.ID,
+ "agent_id": agent.ID,
+ "references": refs,
+ }
+ var text string
+ if len(refs) > 0 {
+ var b strings.Builder
+ b.WriteString(answer)
+ b.WriteString("\n\nSources:\n")
+ for i, r := range refs {
+ title := r.KnowledgeTitle
+ if title == "" {
+ title = r.KnowledgeID
+ }
+ fmt.Fprintf(&b, "[%d] %s (document %s)\n", i+1, title, r.KnowledgeID)
+ }
+ fmt.Fprintf(&b, "\nsession_id: %s", session.ID)
+ text = b.String()
+ } else {
+ text = fmt.Sprintf("%s\n\nsession_id: %s", answer, session.ID)
+ }
+ return mcp.NewToolResultStructured(structured, text), nil
+}
+
+// resolveAskAgent picks the agent configured on the endpoint. Callers cannot
+// name an agent: letting a client choose any tenant agent (or an internal
+// builtin such as the wiki fixer or skill installer, which carry write and
+// shell tools) would bypass the endpoint's tool allowlist.
+func (s *Server) resolveAskAgent(ctx context.Context, ep *types.MCPEndpoint) (*types.CustomAgent, error) {
+ agentID := strings.TrimSpace(ep.DefaultAgentID)
+ if agentID == "" {
+ agentID = types.BuiltinQuickAnswerID
+ }
+ agent, err := s.agentService.GetAgentByID(ctx, agentID)
+ if err != nil || agent == nil {
+ return nil, fmt.Errorf("the agent configured on this endpoint (%q) is not available", agentID)
+ }
+ if !types.MCPEndpointAgentAllowed(agent, ep.TenantID) {
+ return nil, fmt.Errorf("the agent configured on this endpoint (%q) is not available", agentID)
+ }
+ return agent, nil
+}
+
+// resolveAskKnowledgeBases picks the retrieval scope for one ask call:
+// explicit selectors win; otherwise a restricted endpoint pins its own list;
+// otherwise the agent's configuration decides, except that an agent with no
+// knowledge bases of its own falls back to everything the endpoint can see
+// so the call does not fail with "no search targets".
+func (s *Server) resolveAskKnowledgeBases(
+ ctx context.Context, ep *types.MCPEndpoint, agent *types.CustomAgent, requested []string,
+) ([]string, error) {
+ hasRequest := false
+ for _, r := range requested {
+ if strings.TrimSpace(r) != "" {
+ hasRequest = true
+ break
+ }
+ }
+ if hasRequest {
+ kbs, err := s.selectKnowledgeBases(ctx, ep, requested)
+ if err != nil {
+ return nil, err
+ }
+ return knowledgeBaseIDs(kbs), nil
+ }
+ if ep.RestrictsKnowledgeBases() {
+ kbs, err := s.allowedKnowledgeBases(ctx, ep)
+ if err != nil {
+ return nil, err
+ }
+ return knowledgeBaseIDs(kbs), nil
+ }
+ mode := strings.ToLower(strings.TrimSpace(agent.Config.KBSelectionMode))
+ agentHasNoKBs := mode == "none" || ((mode == "selected" || mode == "") && len(agent.Config.KnowledgeBases) == 0)
+ if agentHasNoKBs {
+ kbs, err := s.allowedKnowledgeBases(ctx, ep)
+ if err != nil {
+ return nil, err
+ }
+ return knowledgeBaseIDs(kbs), nil
+ }
+ return nil, nil
+}
+
+func (s *Server) resolveAskSession(
+ ctx context.Context, ep *types.MCPEndpoint, sessionID, question string,
+) (*types.Session, error) {
+ ownerID := types.MCPEndpointPrincipal(ep.TenantID, ep.ID).StorageID()
+ if sessionID = strings.TrimSpace(sessionID); sessionID != "" {
+ session, err := s.sessionService.GetSessionByID(ctx, ep.TenantID, sessionID)
+ if err != nil || session == nil || session.UserID != ownerID {
+ return nil, fmt.Errorf("session %q was not found on this endpoint", sessionID)
+ }
+ return session, nil
+ }
+ title := question
+ if runes := []rune(title); len(runes) > askSessionTitleMaxLen {
+ title = string(runes[:askSessionTitleMaxLen])
+ }
+ created, err := s.sessionService.CreateSession(ctx, &types.Session{
+ TenantID: ep.TenantID,
+ Title: title,
+ Description: "MCP endpoint " + ep.Name,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to create session: %w", err)
+ }
+ if err := s.sessionService.SetSessionOwnerID(ctx, ep.TenantID, created.ID, ownerID); err != nil {
+ return nil, fmt.Errorf("failed to bind session: %w", err)
+ }
+ created.UserID = ownerID
+ return created, nil
+}
+
+// runQA executes one turn synchronously and returns the final answer and
+// the references it cited. It mirrors the IM channel's non-streaming path.
+func (s *Server) runQA(
+ ctx context.Context, session *types.Session, agent *types.CustomAgent, question string, kbIDs []string,
+) (string, []askReference, error) {
+ ctx, cancel := context.WithTimeout(ctx, askTimeout)
+ defer cancel()
+
+ requestID := uuid.New().String()
+ userMsg, err := s.messageService.CreateMessage(ctx, &types.Message{
+ SessionID: session.ID,
+ Role: "user",
+ Content: question,
+ RequestID: requestID,
+ CreatedAt: time.Now(),
+ IsCompleted: true,
+ Channel: askChannel,
+ })
+ if err != nil {
+ return "", nil, fmt.Errorf("failed to create user message: %w", err)
+ }
+ assistantMsg, err := s.messageService.CreateMessage(ctx, &types.Message{
+ SessionID: session.ID,
+ Role: "assistant",
+ RequestID: requestID,
+ CreatedAt: time.Now(),
+ IsCompleted: false,
+ Channel: askChannel,
+ })
+ if err != nil {
+ return "", nil, fmt.Errorf("failed to create assistant message: %w", err)
+ }
+
+ var (
+ mu sync.Mutex
+ answer strings.Builder
+ final string
+ refs []*types.SearchResult
+ qaErr error
+ done = make(chan struct{})
+ complete = make(chan struct{})
+ doneOnce sync.Once
+ compOnce sync.Once
+ )
+ closeDone := func() { doneOnce.Do(func() { close(done) }) }
+ closeComplete := func() { compOnce.Do(func() { close(complete) }) }
+
+ bus := event.NewEventBus()
+ bus.On(event.EventAgentFinalAnswer, func(_ context.Context, evt event.Event) error {
+ data, ok := evt.Data.(event.AgentFinalAnswerData)
+ if !ok {
+ return nil
+ }
+ mu.Lock()
+ answer.WriteString(data.Content)
+ mu.Unlock()
+ if data.Done {
+ closeDone()
+ }
+ return nil
+ })
+ bus.On(event.EventAgentReferences, func(_ context.Context, evt event.Event) error {
+ data, ok := evt.Data.(event.AgentReferencesData)
+ if !ok {
+ return nil
+ }
+ mu.Lock()
+ collectReferences(&refs, data.References)
+ mu.Unlock()
+ return nil
+ })
+ bus.On(event.EventAgentComplete, func(_ context.Context, evt event.Event) error {
+ data, ok := evt.Data.(event.AgentCompleteData)
+ if !ok {
+ return nil
+ }
+ mu.Lock()
+ if data.FinalAnswer != "" {
+ final = data.FinalAnswer
+ }
+ if len(data.KnowledgeRefs) > 0 {
+ var completeRefs []*types.SearchResult
+ collectReferences(&completeRefs, data.KnowledgeRefs)
+ if len(completeRefs) > 0 {
+ refs = completeRefs
+ }
+ }
+ mu.Unlock()
+ closeComplete()
+ return nil
+ })
+ bus.On(event.EventError, func(_ context.Context, evt event.Event) error {
+ data, ok := evt.Data.(event.ErrorData)
+ if !ok {
+ return nil
+ }
+ mu.Lock()
+ qaErr = fmt.Errorf("%s", data.Error)
+ mu.Unlock()
+ closeDone()
+ closeComplete()
+ return nil
+ })
+
+ useAgent := agent.IsAgentMode()
+ go func() {
+ if useAgent {
+ defer closeDone()
+ defer closeComplete()
+ }
+ req := &types.QARequest{
+ Session: session,
+ Query: question,
+ AssistantMessageID: assistantMsg.ID,
+ UserMessageID: userMsg.ID,
+ CustomAgent: agent,
+ KnowledgeBaseIDs: kbIDs,
+ // Web search is never enabled from the MCP surface: the builtin
+ // quick-answer agent turns it on by default, which would make an
+ // otherwise read-only endpoint reach the public internet.
+ WebSearchEnabled: false,
+ }
+ var runErr error
+ if useAgent {
+ runErr = s.sessionService.AgentQA(ctx, req, bus)
+ } else {
+ runErr = s.sessionService.KnowledgeQA(ctx, req, bus)
+ }
+ if runErr != nil {
+ mu.Lock()
+ if qaErr == nil {
+ qaErr = runErr
+ }
+ mu.Unlock()
+ closeDone()
+ closeComplete()
+ }
+ }()
+
+ select {
+ case <-done:
+ if useAgent {
+ timer := time.NewTimer(askCompleteWaitTimeout)
+ select {
+ case <-complete:
+ case <-ctx.Done():
+ case <-timer.C:
+ logger.Warnf(ctx, "[mcpserver] ask timed out waiting for agent completion: session=%s", session.ID)
+ }
+ timer.Stop()
+ }
+ case <-ctx.Done():
+ assistantMsg.Content = "The answer was interrupted before completion."
+ assistantMsg.IsCompleted = true
+ if updateErr := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); updateErr != nil {
+ logger.Warnf(ctx, "[mcpserver] failed to finalize interrupted message: %v", updateErr)
+ }
+ return "", nil, fmt.Errorf("answer timed out: %w", ctx.Err())
+ }
+
+ mu.Lock()
+ text := answer.String()
+ if strings.TrimSpace(text) == "" && final != "" {
+ text = final
+ }
+ collected := append([]*types.SearchResult(nil), refs...)
+ runErr := qaErr
+ mu.Unlock()
+
+ if strings.TrimSpace(text) == "" && runErr != nil {
+ assistantMsg.Content = "The answer failed: " + runErr.Error()
+ assistantMsg.IsCompleted = true
+ if updateErr := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); updateErr != nil {
+ logger.Warnf(ctx, "[mcpserver] failed to finalize failed message: %v", updateErr)
+ }
+ return "", nil, runErr
+ }
+ if strings.TrimSpace(text) == "" {
+ text = "No answer could be produced for this question."
+ }
+ assistantMsg.Content = text
+ assistantMsg.IsCompleted = true
+ if len(collected) > 0 {
+ assistantMsg.KnowledgeReferences = types.References(collected)
+ }
+ if err := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); err != nil {
+ logger.Warnf(ctx, "[mcpserver] failed to persist assistant message: %v", err)
+ }
+ return text, summarizeReferences(collected), nil
+}
+
+func collectReferences(dst *[]*types.SearchResult, raw interface{}) {
+ switch v := raw.(type) {
+ case []*types.SearchResult:
+ *dst = append(*dst, v...)
+ case []interface{}:
+ for _, item := range v {
+ if sr, ok := item.(*types.SearchResult); ok {
+ *dst = append(*dst, sr)
+ }
+ }
+ }
+}
+
+const askExcerptMaxRunes = 300
+
+func summarizeReferences(refs []*types.SearchResult) []askReference {
+ out := make([]askReference, 0, len(refs))
+ seen := map[string]struct{}{}
+ for _, r := range refs {
+ if r == nil {
+ continue
+ }
+ key := r.ID
+ if key == "" {
+ key = r.KnowledgeID + ":" + fmt.Sprint(r.ChunkIndex)
+ }
+ if _, dup := seen[key]; dup {
+ continue
+ }
+ seen[key] = struct{}{}
+ excerpt := strings.TrimSpace(r.Content)
+ if runes := []rune(excerpt); len(runes) > askExcerptMaxRunes {
+ excerpt = string(runes[:askExcerptMaxRunes]) + "…"
+ }
+ out = append(out, askReference{
+ KnowledgeID: r.KnowledgeID,
+ KnowledgeTitle: r.KnowledgeTitle,
+ ChunkID: r.ID,
+ Score: r.Score,
+ Excerpt: excerpt,
+ })
+ }
+ return out
+}
diff --git a/internal/mcpserver/tools_ingest.go b/internal/mcpserver/tools_ingest.go
new file mode 100644
index 000000000..658bbad0c
--- /dev/null
+++ b/internal/mcpserver/tools_ingest.go
@@ -0,0 +1,175 @@
+package mcpserver
+
+import (
+ "context"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/application/access"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+func addDocumentTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolAddDocument,
+ mcp.WithDescription("Add a document to a knowledge base from Markdown text or from a URL. Text documents "+
+ "are stored as editable Markdown pages; URLs are fetched and parsed asynchronously. Returns the new "+
+ "document id."),
+ mcp.WithString("knowledge_base_id", mcp.Required(), mcp.Description("Knowledge base id or exact name")),
+ mcp.WithString("title", mcp.Required(), mcp.Description("Document title")),
+ mcp.WithString("content", mcp.Description("Markdown content; required unless url is given")),
+ mcp.WithString("url", mcp.Description("Web page or file URL to import instead of content")),
+ mcp.WithBoolean("publish", mcp.Description("For text documents: publish immediately (default true) or keep "+
+ "as draft")),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ )
+}
+
+func updateDocumentTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolUpdateDocument,
+ mcp.WithDescription("Replace the content (and optionally the title) of a Markdown document created from "+
+ "text. The document is re-indexed asynchronously."),
+ mcp.WithString("knowledge_id", mcp.Required(), mcp.Description("Document id")),
+ mcp.WithString("content", mcp.Required(), mcp.Description("New Markdown content")),
+ mcp.WithString("title", mcp.Description("New title; keeps the current title when omitted")),
+ mcp.WithBoolean("publish", mcp.Description("Publish (default true) or keep as draft")),
+ mcp.WithDestructiveHintAnnotation(true),
+ )
+}
+
+func deleteDocumentTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolDeleteDocument,
+ mcp.WithDescription("Permanently delete a document and its index data from its knowledge base."),
+ mcp.WithString("knowledge_id", mcp.Required(), mcp.Description("Document id")),
+ mcp.WithDestructiveHintAnnotation(true),
+ )
+}
+
+func manualStatus(publish bool) string {
+ if publish {
+ return types.ManualKnowledgeStatusPublish
+ }
+ return types.ManualKnowledgeStatusDraft
+}
+
+func (s *Server) handleAddDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ selector, err := req.RequireString("knowledge_base_id")
+ if err != nil {
+ return mcp.NewToolResultError("knowledge_base_id is required"), nil
+ }
+ title := strings.TrimSpace(req.GetString("title", ""))
+ if title == "" {
+ return mcp.NewToolResultError("title is required"), nil
+ }
+ content := req.GetString("content", "")
+ url := strings.TrimSpace(req.GetString("url", ""))
+ if strings.TrimSpace(content) == "" && url == "" {
+ return mcp.NewToolResultError("either content or url is required"), nil
+ }
+ kbs, err := s.selectKnowledgeBases(ctx, ep, []string{selector})
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ kb := kbs[0]
+ ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleEditor)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ if err := access.RequireKBWrite(ctx, kb); err != nil {
+ return mcp.NewToolResultError("this endpoint is not allowed to write to knowledge base " + kb.ID), nil
+ }
+
+ var created *types.Knowledge
+ if url != "" {
+ created, err = s.knowledgeService.CreateKnowledgeFromURL(
+ ctx, kb.ID, url, "", "", nil, title, nil, askChannel, nil,
+ )
+ } else {
+ created, err = s.knowledgeService.CreateKnowledgeFromManual(ctx, kb.ID, &types.ManualKnowledgePayload{
+ Title: title,
+ Content: content,
+ Status: manualStatus(req.GetBool("publish", true)),
+ Channel: askChannel,
+ }, askChannel)
+ }
+ if err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to add document", err), nil
+ }
+ return jsonResult(map[string]any{
+ "knowledge_base_id": kb.ID,
+ "document": summarizeKnowledge(created),
+ "note": "Indexing runs asynchronously; the document becomes searchable once parse_status is " +
+ "completed.",
+ })
+}
+
+func (s *Server) handleUpdateDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ knowledgeID, err := req.RequireString("knowledge_id")
+ if err != nil {
+ return mcp.NewToolResultError("knowledge_id is required"), nil
+ }
+ content := req.GetString("content", "")
+ if strings.TrimSpace(content) == "" {
+ return mcp.NewToolResultError("content is required"), nil
+ }
+ existing, kb, err := s.knowledgeInScope(ctx, ep, knowledgeID)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleEditor)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ title := strings.TrimSpace(req.GetString("title", ""))
+ if title == "" {
+ title = existing.Title
+ }
+ updated, err := s.knowledgeService.UpdateManualKnowledge(ctx, existing.ID, &types.ManualKnowledgePayload{
+ Title: title,
+ Content: content,
+ Status: manualStatus(req.GetBool("publish", true)),
+ Channel: askChannel,
+ })
+ if err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to update document", err), nil
+ }
+ return jsonResult(map[string]any{
+ "document": summarizeKnowledge(updated),
+ "note": "Re-indexing runs asynchronously.",
+ })
+}
+
+func (s *Server) handleDeleteDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ knowledgeID, err := req.RequireString("knowledge_id")
+ if err != nil {
+ return mcp.NewToolResultError("knowledge_id is required"), nil
+ }
+ existing, kb, err := s.knowledgeInScope(ctx, ep, knowledgeID)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleEditor)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ if err := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to delete document", err), nil
+ }
+ return jsonResult(map[string]any{
+ "deleted": true,
+ "knowledge_id": existing.ID,
+ "title": existing.Title,
+ })
+}
diff --git a/internal/mcpserver/tools_retrieve.go b/internal/mcpserver/tools_retrieve.go
new file mode 100644
index 000000000..bf4aa1242
--- /dev/null
+++ b/internal/mcpserver/tools_retrieve.go
@@ -0,0 +1,312 @@
+package mcpserver
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+const (
+ defaultListPageSize = 20
+ maxListPageSize = 100
+ defaultChunkLimit = 20
+ maxChunkLimit = 100
+)
+
+func listKnowledgeBasesTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolListKnowledgeBases,
+ mcp.WithDescription("List the knowledge bases this endpoint can access, with their id, name, description "+
+ "and which retrieval modes (semantic, keyword, wiki) each supports. Call this first to learn what is in "+
+ "scope; other tools accept either the id or the exact name."),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+func searchKnowledgeTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolSearchKnowledge,
+ mcp.WithDescription("Semantic search across the knowledge bases in scope. Returns the most relevant "+
+ "passages with their document ids and titles. Use a natural-language question or topic; use grep_chunks "+
+ "instead for exact keywords, codes or names."),
+ mcp.WithString("query", mcp.Required(), mcp.Description("A natural-language question or topic to search for")),
+ mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
+ mcp.Description("Optional knowledge base ids or names to restrict the search; defaults to every "+
+ "knowledge base in scope")),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+func grepChunksTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolGrepChunks,
+ mcp.WithDescription("Case-insensitive regular-expression search over the raw text chunks of the knowledge "+
+ "bases in scope. Best for exact terms, identifiers, error codes or product names that semantic search "+
+ "may miss."),
+ mcp.WithString("query", mcp.Required(), mcp.Description("Regular expression (POSIX, case-insensitive) to "+
+ "match against chunk text")),
+ mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
+ mcp.Description("Optional knowledge base ids or names to restrict the search")),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+func listDocumentsTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolListDocuments,
+ mcp.WithDescription("List the documents inside one knowledge base with pagination and an optional title "+
+ "keyword filter. Returns document ids that read_document accepts."),
+ mcp.WithString("knowledge_base_id", mcp.Required(), mcp.Description("Knowledge base id or exact name")),
+ mcp.WithString("keyword", mcp.Description("Optional substring to filter document titles")),
+ mcp.WithNumber("page", mcp.Description("1-based page number, default 1")),
+ mcp.WithNumber("page_size", mcp.Description("Documents per page, default 20, max 100")),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+func readDocumentTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolReadDocument,
+ mcp.WithDescription("Read a document's metadata and its text chunks in order. Page through long documents "+
+ "with offset and limit."),
+ mcp.WithString("knowledge_id", mcp.Required(),
+ mcp.Description("Document id from search results or list_documents")),
+ mcp.WithNumber("offset", mcp.Description("Chunk offset to start from, default 0")),
+ mcp.WithNumber("limit", mcp.Description("Number of chunks to return, default 20, max 100")),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+type knowledgeBaseSummary struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Type string `json:"type"`
+ Capabilities []string `json:"capabilities"`
+}
+
+func summarizeKnowledgeBase(kb *types.KnowledgeBase) knowledgeBaseSummary {
+ caps := []string{}
+ if kb.IsVectorEnabled() {
+ caps = append(caps, "semantic")
+ }
+ if kb.IsKeywordEnabled() {
+ caps = append(caps, "keyword")
+ }
+ if kb.IsWikiEnabled() {
+ caps = append(caps, "wiki")
+ }
+ return knowledgeBaseSummary{
+ ID: kb.ID,
+ Name: kb.Name,
+ Description: kb.Description,
+ Type: kb.Type,
+ Capabilities: caps,
+ }
+}
+
+func (s *Server) handleListKnowledgeBases(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ kbs, err := s.allowedKnowledgeBases(ctx, ep)
+ if err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to list knowledge bases", err), nil
+ }
+ out := make([]knowledgeBaseSummary, 0, len(kbs))
+ for _, kb := range kbs {
+ out = append(out, summarizeKnowledgeBase(kb))
+ }
+ return jsonResult(map[string]any{"knowledge_bases": out, "total": len(out)})
+}
+
+func (s *Server) handleSearchKnowledge(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ query, err := req.RequireString("query")
+ if err != nil || strings.TrimSpace(query) == "" {
+ return mcp.NewToolResultError("query is required"), nil
+ }
+ kbs, err := s.selectKnowledgeBases(ctx, ep, req.GetStringSlice("knowledge_base_ids", nil))
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ kbs = retrievableKnowledgeBases(kbs)
+ if len(kbs) == 0 {
+ return mcp.NewToolResultError(
+ "none of the selected knowledge bases supports semantic or keyword retrieval"), nil
+ }
+ tool := tools.NewKnowledgeSearchTool(
+ s.kbService, s.knowledgeService, s.chunkService, searchTargetsFor(kbs), nil, s.cfg,
+ )
+ args, _ := json.Marshal(map[string]any{
+ "queries": []string{strings.TrimSpace(query)},
+ "knowledge_base_ids": knowledgeBaseIDs(kbs),
+ })
+ res, execErr := tool.Execute(ctx, args)
+ return toolResultFromAgentTool(res, execErr), nil
+}
+
+func (s *Server) handleGrepChunks(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ query, err := req.RequireString("query")
+ if err != nil || strings.TrimSpace(query) == "" {
+ return mcp.NewToolResultError("query is required"), nil
+ }
+ kbs, err := s.selectKnowledgeBases(ctx, ep, req.GetStringSlice("knowledge_base_ids", nil))
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ tool := tools.NewGrepChunksTool(s.db, searchTargetsFor(kbs))
+ args, _ := json.Marshal(map[string]any{"query": strings.TrimSpace(query)})
+ res, execErr := tool.Execute(ctx, args)
+ return toolResultFromAgentTool(res, execErr), nil
+}
+
+type documentSummary struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ FileName string `json:"file_name,omitempty"`
+ FileType string `json:"file_type,omitempty"`
+ Source string `json:"source,omitempty"`
+ ParseStatus string `json:"parse_status"`
+ Description string `json:"description,omitempty"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func summarizeKnowledge(k *types.Knowledge) documentSummary {
+ return documentSummary{
+ ID: k.ID,
+ Title: k.Title,
+ FileName: k.FileName,
+ FileType: k.FileType,
+ Source: k.Source,
+ ParseStatus: k.ParseStatus,
+ Description: k.Description,
+ CreatedAt: k.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
+ UpdatedAt: k.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
+ }
+}
+
+func (s *Server) handleListDocuments(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ selector, err := req.RequireString("knowledge_base_id")
+ if err != nil {
+ return mcp.NewToolResultError("knowledge_base_id is required"), nil
+ }
+ kbs, err := s.selectKnowledgeBases(ctx, ep, []string{selector})
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ kb := kbs[0]
+ // Documents live under the knowledge base owner; run the listing there.
+ ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleViewer)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ page := req.GetInt("page", 1)
+ if page < 1 {
+ page = 1
+ }
+ pageSize := req.GetInt("page_size", defaultListPageSize)
+ if pageSize < 1 {
+ pageSize = defaultListPageSize
+ }
+ if pageSize > maxListPageSize {
+ pageSize = maxListPageSize
+ }
+ result, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(
+ ctx, kb.ID,
+ &types.Pagination{Page: page, PageSize: pageSize},
+ types.KnowledgeListFilter{Keyword: strings.TrimSpace(req.GetString("keyword", ""))},
+ )
+ if err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to list documents", err), nil
+ }
+ docs := []documentSummary{}
+ if rows, ok := result.Data.([]*types.Knowledge); ok {
+ for _, k := range rows {
+ docs = append(docs, summarizeKnowledge(k))
+ }
+ }
+ return jsonResult(map[string]any{
+ "knowledge_base_id": kb.ID,
+ "total": result.Total,
+ "page": result.Page,
+ "page_size": result.PageSize,
+ "documents": docs,
+ })
+}
+
+func (s *Server) handleReadDocument(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ knowledgeID, err := req.RequireString("knowledge_id")
+ if err != nil {
+ return mcp.NewToolResultError("knowledge_id is required"), nil
+ }
+ k, kb, err := s.knowledgeInScope(ctx, ep, knowledgeID)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ ctx, err = s.scopedKBContext(ctx, kb, types.OrgRoleViewer)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ limit := req.GetInt("limit", defaultChunkLimit)
+ if limit < 1 {
+ limit = defaultChunkLimit
+ }
+ if limit > maxChunkLimit {
+ limit = maxChunkLimit
+ }
+ offset := req.GetInt("offset", 0)
+ if offset < 0 {
+ offset = 0
+ }
+ tool := tools.NewListKnowledgeChunksTool(
+ s.knowledgeService, s.chunkService, searchTargetsFor([]*types.KnowledgeBase{kb}),
+ )
+ args, _ := json.Marshal(map[string]any{
+ "knowledge_id": k.ID,
+ "limit": limit,
+ "offset": offset,
+ })
+ res, execErr := tool.Execute(ctx, args)
+ if execErr != nil || res == nil || !res.Success {
+ return toolResultFromAgentTool(res, execErr), nil
+ }
+ header := fmt.Sprintf("Document: %s\nID: %s\nKnowledge base: %s (%s)\nType: %s\nStatus: %s\n",
+ k.Title, k.ID, kb.Name, kb.ID, k.FileType, k.ParseStatus)
+ if k.Description != "" {
+ header += "Summary: " + k.Description + "\n"
+ }
+ res.Output = header + "\n" + res.Output
+ if res.Data == nil {
+ res.Data = map[string]interface{}{}
+ }
+ res.Data["document"] = summarizeKnowledge(k)
+ return toolResultFromAgentTool(res, nil), nil
+}
+
+// jsonResult renders structured data both as text (for clients that only
+// read content) and as structuredContent.
+func jsonResult(v any) (*mcp.CallToolResult, error) {
+ raw, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to encode result", err), nil
+ }
+ return mcp.NewToolResultStructured(v, string(raw)), nil
+}
diff --git a/internal/mcpserver/tools_wiki.go b/internal/mcpserver/tools_wiki.go
new file mode 100644
index 000000000..109f40b9d
--- /dev/null
+++ b/internal/mcpserver/tools_wiki.go
@@ -0,0 +1,158 @@
+package mcpserver
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+const (
+ defaultWikiSearchLimit = 10
+ maxWikiSearchLimit = 50
+ defaultWikiIndexLimit = 50
+ maxWikiIndexLimit = 200
+)
+
+func wikiSearchTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolWikiSearch,
+ mcp.WithDescription("Search the generated wiki pages of the knowledge bases in scope by title, alias and "+
+ "content. Returns page slugs that wiki_read_page accepts. Only knowledge bases with a wiki are "+
+ "searched."),
+ mcp.WithString("query", mcp.Required(), mcp.Description("Search terms or a regular expression")),
+ mcp.WithArray("knowledge_base_ids", mcp.WithStringItems(),
+ mcp.Description("Optional knowledge base ids or names to restrict the search")),
+ mcp.WithNumber("limit", mcp.Description("Maximum pages to return, default 10, max 50")),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+func wikiReadPageTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolWikiReadPage,
+ mcp.WithDescription("Read one wiki page by slug, including its content and outgoing links."),
+ mcp.WithString("slug", mcp.Required(), mcp.Description("Page slug from wiki_search or wiki_index, e.g. "+
+ "concept/rag")),
+ mcp.WithString("knowledge_base_id", mcp.Description("Knowledge base id or name, required only when the same "+
+ "slug exists in several wikis")),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+func wikiIndexTool() mcp.Tool {
+ return mcp.NewTool(types.MCPEndpointToolWikiIndex,
+ mcp.WithDescription("Browse the table of contents of one knowledge base's wiki: the intro plus pages "+
+ "grouped by type (summary, entity, concept, ...)."),
+ mcp.WithString("knowledge_base_id", mcp.Required(), mcp.Description("Knowledge base id or exact name")),
+ mcp.WithNumber("limit", mcp.Description("Maximum entries per page type, default 50, max 200")),
+ mcp.WithReadOnlyHintAnnotation(true),
+ )
+}
+
+func (s *Server) wikiScopeFromRequest(
+ ctx context.Context, ep *types.MCPEndpoint, requested []string,
+) ([]*types.KnowledgeBase, error) {
+ kbs, err := s.selectKnowledgeBases(ctx, ep, requested)
+ if err != nil {
+ return nil, err
+ }
+ kbs = wikiKnowledgeBases(kbs)
+ if len(kbs) == 0 {
+ return nil, errNoWikiInScope
+ }
+ return kbs, nil
+}
+
+var errNoWikiInScope = &toolError{"none of the selected knowledge bases has a wiki; call list_knowledge_bases and " +
+ "pick one whose capabilities include \"wiki\""}
+
+type toolError struct{ msg string }
+
+func (e *toolError) Error() string { return e.msg }
+
+func (s *Server) handleWikiSearch(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ query, err := req.RequireString("query")
+ if err != nil || strings.TrimSpace(query) == "" {
+ return mcp.NewToolResultError("query is required"), nil
+ }
+ kbs, err := s.wikiScopeFromRequest(ctx, ep, req.GetStringSlice("knowledge_base_ids", nil))
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ limit := req.GetInt("limit", defaultWikiSearchLimit)
+ if limit < 1 {
+ limit = defaultWikiSearchLimit
+ }
+ if limit > maxWikiSearchLimit {
+ limit = maxWikiSearchLimit
+ }
+ tool := tools.NewWikiSearchTool(s.wikiService, s.knowledgeService, wikiScopesFor(kbs), tools.NewWikiRouteResolver())
+ args, _ := json.Marshal(map[string]any{
+ "queries": []string{strings.TrimSpace(query)},
+ "limit": limit,
+ })
+ res, execErr := tool.Execute(ctx, args)
+ return toolResultFromAgentTool(res, execErr), nil
+}
+
+func (s *Server) handleWikiReadPage(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ slug, err := req.RequireString("slug")
+ if err != nil || strings.TrimSpace(slug) == "" {
+ return mcp.NewToolResultError("slug is required"), nil
+ }
+ var requested []string
+ if kbSel := strings.TrimSpace(req.GetString("knowledge_base_id", "")); kbSel != "" {
+ requested = []string{kbSel}
+ }
+ kbs, err := s.wikiScopeFromRequest(ctx, ep, requested)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ tool := tools.NewWikiReadPageTool(
+ s.wikiService, s.knowledgeService, wikiScopesFor(kbs), tools.NewWikiRouteResolver(),
+ )
+ args, _ := json.Marshal(map[string]any{"slug": strings.TrimSpace(slug)})
+ res, execErr := tool.Execute(ctx, args)
+ return toolResultFromAgentTool(res, execErr), nil
+}
+
+func (s *Server) handleWikiIndex(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ep, err := endpointFromContext(ctx)
+ if err != nil {
+ return mcp.NewToolResultError("unauthorized"), nil
+ }
+ selector, err := req.RequireString("knowledge_base_id")
+ if err != nil {
+ return mcp.NewToolResultError("knowledge_base_id is required"), nil
+ }
+ kbs, err := s.wikiScopeFromRequest(ctx, ep, []string{selector})
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ limit := req.GetInt("limit", defaultWikiIndexLimit)
+ if limit < 1 {
+ limit = defaultWikiIndexLimit
+ }
+ if limit > maxWikiIndexLimit {
+ limit = maxWikiIndexLimit
+ }
+ view, err := s.wikiService.GetIndexView(ctx, kbs[0].ID, nil, limit, "")
+ if err != nil {
+ return mcp.NewToolResultErrorFromErr("failed to load wiki index", err), nil
+ }
+ return jsonResult(map[string]any{
+ "knowledge_base_id": kbs[0].ID,
+ "intro": view.Intro,
+ "groups": view.Groups,
+ })
+}
diff --git a/internal/middleware/mcp_endpoint_auth.go b/internal/middleware/mcp_endpoint_auth.go
new file mode 100644
index 000000000..9aabeaf19
--- /dev/null
+++ b/internal/middleware/mcp_endpoint_auth.go
@@ -0,0 +1,95 @@
+package middleware
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+// MCPEndpointAuth authenticates calls on the workspace MCP server surface
+// (/mcp/:endpoint_id). The client presents the endpoint's bearer token; on
+// success the request carries the endpoint's workspace, a synthetic machine
+// user, an MCP-endpoint principal and an API-key style scope derived from the
+// endpoint's tool allowlist and knowledge-base scope, so every downstream
+// service applies the same checks it applies to a scoped API key.
+func MCPEndpointAuth(svc interfaces.MCPEndpointService, tenantSvc interfaces.TenantService) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ endpointID := strings.TrimSpace(c.Param("endpoint_id"))
+ token := extractMCPEndpointToken(c)
+ if endpointID == "" || token == "" {
+ c.Header("WWW-Authenticate", `Bearer realm="weknora-mcp"`)
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: missing bearer token"})
+ c.Abort()
+ return
+ }
+ ep, err := svc.Authenticate(c.Request.Context(), endpointID, token)
+ if err != nil {
+ switch {
+ case errors.Is(err, service.ErrMCPEndpointDisabled):
+ c.JSON(http.StatusForbidden, gin.H{"error": "mcp endpoint disabled"})
+ case errors.Is(err, service.ErrMCPEndpointTokenInvalid), errors.Is(err, service.ErrMCPEndpointNotFound):
+ c.Header("WWW-Authenticate", `Bearer realm="weknora-mcp"`)
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: invalid token"})
+ default:
+ logger.Warnf(c.Request.Context(), "[mcp-endpoint] auth lookup failed: %v", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "authentication unavailable"})
+ }
+ c.Abort()
+ return
+ }
+ tenant, err := tenantSvc.GetTenantByID(c.Request.Context(), ep.TenantID)
+ if err != nil || tenant == nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "workspace unavailable"})
+ c.Abort()
+ return
+ }
+ if strings.EqualFold(tenant.Status, "inactive") || strings.EqualFold(tenant.Status, "disabled") {
+ c.JSON(http.StatusForbidden, gin.H{"error": "workspace inactive"})
+ c.Abort()
+ return
+ }
+
+ scope := types.MCPEndpointScope(ep)
+ user := &types.User{
+ ID: fmt.Sprintf("mcp-%s", ep.ID),
+ Username: fmt.Sprintf("mcp-%s", ep.ID),
+ Email: fmt.Sprintf("mcp-%[email protected]", ep.ID),
+ TenantID: ep.TenantID,
+ IsActive: true,
+ }
+ applyAuthSession(c, authSession{
+ User: user,
+ Principal: types.MCPEndpointPrincipal(ep.TenantID, ep.ID),
+ TenantID: ep.TenantID,
+ Tenant: tenant,
+ Role: types.TenantRoleViewer,
+ APIKeyScope: &scope,
+ Extra: map[types.ContextKey]any{types.MCPEndpointContextKey: ep},
+ })
+ c.Next()
+ }
+}
+
+// extractMCPEndpointToken reads "Authorization: Bearer mcp_..." only. Query
+// string tokens are rejected so they never land in access logs.
+func extractMCPEndpointToken(c *gin.Context) string {
+ auth := strings.TrimSpace(c.GetHeader("Authorization"))
+ if len(auth) > 7 && strings.EqualFold(auth[:7], "Bearer ") {
+ return strings.TrimSpace(auth[7:])
+ }
+ return ""
+}
+
+// MCPEndpointFromContext returns the endpoint authenticated for this request.
+func MCPEndpointFromContext(ctx context.Context) (*types.MCPEndpoint, bool) {
+ ep, ok := ctx.Value(types.MCPEndpointContextKey).(*types.MCPEndpoint)
+ return ep, ok && ep != nil
+}
diff --git a/internal/middleware/mcp_endpoint_auth_test.go b/internal/middleware/mcp_endpoint_auth_test.go
new file mode 100644
index 000000000..1e9f29540
--- /dev/null
+++ b/internal/middleware/mcp_endpoint_auth_test.go
@@ -0,0 +1,126 @@
+package middleware
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+type fakeMCPEndpointService struct {
+ interfaces.MCPEndpointService
+ ep *types.MCPEndpoint
+ token string
+}
+
+func (f *fakeMCPEndpointService) Authenticate(_ context.Context, endpointID, token string) (*types.MCPEndpoint, error) {
+ if f.ep == nil || endpointID != f.ep.ID || token != f.token {
+ return nil, service.ErrMCPEndpointTokenInvalid
+ }
+ if !f.ep.Enabled {
+ return nil, service.ErrMCPEndpointDisabled
+ }
+ return f.ep, nil
+}
+
+func newMCPAuthTestEngine(svc *fakeMCPEndpointService, capture *map[string]any) *gin.Engine {
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ r.ContextWithFallback = true
+ tenantSvc := &fakeTenantService{tenant: &types.Tenant{ID: 42, Status: "active"}}
+ r.POST("/mcp/:endpoint_id", MCPEndpointAuth(svc, tenantSvc), func(c *gin.Context) {
+ ctx := c.Request.Context()
+ ep, _ := MCPEndpointFromContext(ctx)
+ scope, _ := types.TenantAPIKeyScopeFromContext(ctx)
+ tenantID, _ := types.TenantIDFromContext(ctx)
+ principal, _ := types.PrincipalFromContext(ctx)
+ *capture = map[string]any{
+ "endpoint": ep,
+ "scope": scope,
+ "tenant": tenantID,
+ "principal": principal,
+ }
+ c.Status(http.StatusNoContent)
+ })
+ return r
+}
+
+func TestMCPEndpointAuthAttachesScopeAndPrincipal(t *testing.T) {
+ ep := &types.MCPEndpoint{
+ ID: "ep-1", TenantID: 42, Enabled: true,
+ KnowledgeBaseIDs: types.StringArray{"kb-9"},
+ Tools: types.StringArray{types.MCPEndpointToolAsk},
+ }
+ svc := &fakeMCPEndpointService{ep: ep, token: "mcp_secret"}
+ var captured map[string]any
+ r := newMCPAuthTestEngine(svc, &captured)
+
+ req := httptest.NewRequest(http.MethodPost, "/mcp/ep-1", nil)
+ req.Header.Set("Authorization", "Bearer mcp_secret")
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("status %d body %s", w.Code, w.Body.String())
+ }
+ if got, _ := captured["endpoint"].(*types.MCPEndpoint); got == nil || got.ID != "ep-1" {
+ t.Fatalf("endpoint missing from context: %v", captured["endpoint"])
+ }
+ if got, _ := captured["tenant"].(uint64); got != 42 {
+ t.Fatalf("tenant = %v", captured["tenant"])
+ }
+ scope := captured["scope"].(types.TenantAPIKeyScope)
+ if scope.FullAccess || !scope.AllowsKnowledgeBase("kb-9") || scope.AllowsKnowledgeBase("kb-1") {
+ t.Fatalf("scope not derived from endpoint: %+v", scope)
+ }
+ if !scope.HasCapability(types.APIKeyCapabilityChat) {
+ t.Fatalf("ask tool must grant chat capability: %+v", scope)
+ }
+ principal := captured["principal"].(types.Principal)
+ if principal.Type != types.PrincipalMCPEndpoint || principal.ID != "42:ep-1" {
+ t.Fatalf("principal = %+v", principal)
+ }
+}
+
+func TestMCPEndpointAuthRejectsBadTokens(t *testing.T) {
+ ep := &types.MCPEndpoint{ID: "ep-1", TenantID: 42, Enabled: true}
+ svc := &fakeMCPEndpointService{ep: ep, token: "mcp_secret"}
+ var captured map[string]any
+ r := newMCPAuthTestEngine(svc, &captured)
+
+ cases := []struct {
+ name string
+ path string
+ header string
+ want int
+ }{
+ {"missing header", "/mcp/ep-1", "", http.StatusUnauthorized},
+ {"wrong scheme", "/mcp/ep-1", "Embed mcp_secret", http.StatusUnauthorized},
+ {"wrong token", "/mcp/ep-1", "Bearer mcp_other", http.StatusUnauthorized},
+ {"wrong endpoint", "/mcp/ep-2", "Bearer mcp_secret", http.StatusUnauthorized},
+ }
+ for _, tc := range cases {
+ req := httptest.NewRequest(http.MethodPost, tc.path, nil)
+ if tc.header != "" {
+ req.Header.Set("Authorization", tc.header)
+ }
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ if w.Code != tc.want {
+ t.Errorf("%s: status %d, want %d", tc.name, w.Code, tc.want)
+ }
+ }
+
+ ep.Enabled = false
+ req := httptest.NewRequest(http.MethodPost, "/mcp/ep-1", nil)
+ req.Header.Set("Authorization", "Bearer mcp_secret")
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("disabled endpoint: status %d, want 403", w.Code)
+ }
+}
diff --git a/internal/router/deployment_capabilities.go b/internal/router/deployment_capabilities.go
index aab2f63a8..e9a05aba2 100644
--- a/internal/router/deployment_capabilities.go
+++ b/internal/router/deployment_capabilities.go
@@ -12,7 +12,9 @@ func deploymentCapabilitiesFromRouter(params RouterParams) handler.DeploymentCap
IM: params.IMHandler != nil,
// Match RegisterEmbedChannelRoutes: management routes depend on handler only.
Embed: params.EmbedChannelHandler != nil,
- API: params.TenantHandler != nil && params.TenantAPIKeyService != nil,
+ // Match RegisterMCPEndpointRoutes / RegisterMCPServerRoutes.
+ MCPServer: params.MCPEndpointHandler != nil && params.MCPServer != nil && params.MCPEndpointService != nil,
+ API: params.TenantHandler != nil && params.TenantAPIKeyService != nil,
MCP: params.MCPServiceHandler != nil &&
params.MCPCredentialsHandler != nil &&
params.MCPOAuthHandler != nil,
diff --git a/internal/router/router.go b/internal/router/router.go
index 05346e5d1..9eb920e31 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -17,6 +17,7 @@ import (
"github.com/Tencent/WeKnora/internal/handler"
"github.com/Tencent/WeKnora/internal/handler/session"
"github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/mcpserver"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -82,6 +83,9 @@ type RouterParams struct {
IMHandler *handler.IMHandler
EmbedChannelHandler *handler.EmbedChannelHandler
EmbedChannelService interfaces.EmbedChannelService
+ MCPEndpointHandler *handler.MCPEndpointHandler
+ MCPEndpointService interfaces.MCPEndpointService
+ MCPServer *mcpserver.Server
RedisClient *redis.Client
DataSourceHandler *handler.DataSourceHandler
DataSourceCredentialsHandler *handler.DataSourceCredentialsHandler
@@ -117,8 +121,11 @@ func NewRouter(params RouterParams) *gin.Engine {
AllowHeaders: []string{
"Origin", "Content-Type", "Accept", "Authorization", "X-API-Key", "X-Request-ID", "X-Tenant-ID",
"X-Embed-Session", "X-External-User-ID", "X-External-User-Token", "X-WeKnora-Desktop-Token",
+ // Streamable HTTP MCP clients running in a browser send these on
+ // the /mcp/:endpoint_id surface.
+ "MCP-Protocol-Version", "Mcp-Session-Id", "Last-Event-ID",
},
- ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin"},
+ ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Mcp-Session-Id"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
@@ -175,6 +182,10 @@ func NewRouter(params RouterParams) *gin.Engine {
params.ResourceCatalog,
)
+ // Workspace MCP server surface (/mcp/:endpoint_id): bearer-token auth per
+ // endpoint, so it must precede the global Auth middleware.
+ RegisterMCPServerRoutes(r, params.MCPServer, params.MCPEndpointService, params.TenantService)
+
// Short-lived capability URLs for IM and other clients that cannot attach
// WeKnora authentication headers.
serveResourceGrants(r, params.ResourceCatalog, params.TenantService, params.FileService, params.StorageBackendResolver)
@@ -305,6 +316,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterOrganizationRoutes(v1, params.OrganizationHandler, rbacGuards)
RegisterIMChannelRoutes(v1, params.IMHandler, rbacGuards)
RegisterEmbedChannelRoutes(v1, params.EmbedChannelHandler, rbacGuards)
+ RegisterMCPEndpointRoutes(v1, params.MCPEndpointHandler, rbacGuards)
RegisterDataSourceRoutes(v1, params.DataSourceHandler, params.DataSourceCredentialsHandler, rbacGuards)
RegisterWeKnoraCloudRoutes(v1, params.WeKnoraCloudHandler, rbacGuards)
RegisterWikiPageRoutes(v1, params.WikiPageHandler, rbacGuards)
diff --git a/internal/router/routes_mcp_endpoint.go b/internal/router/routes_mcp_endpoint.go
new file mode 100644
index 000000000..aa7b622a2
--- /dev/null
+++ b/internal/router/routes_mcp_endpoint.go
@@ -0,0 +1,48 @@
+package router
+
+import (
+ "net/http"
+
+ "github.com/Tencent/WeKnora/internal/handler"
+ "github.com/Tencent/WeKnora/internal/mcpserver"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+// RegisterMCPEndpointRoutes registers the management API for workspace MCP
+// endpoints. Endpoints are tenant-wide integration surfaces like embed
+// channels: reads for every member, mutations for admins, and API keys need
+// the manage_channels capability.
+func RegisterMCPEndpointRoutes(r *gin.RouterGroup, h *handler.MCPEndpointHandler, g *rbacGuards) {
+ if h == nil {
+ return
+ }
+ grp := g.apiKeyGroup(r.Group("/mcp-endpoints"), apiKeyManageChannels(apiKeyFullAccess()))
+ grp.GET("", g.Viewer(), h.ListMCPEndpoints)
+ grp.GET("/tools", g.Viewer(), h.ListToolCatalog)
+ grp.POST("", g.Admin(), h.CreateMCPEndpoint)
+ grp.GET("/:endpoint_id", g.Viewer(), h.GetMCPEndpoint)
+ grp.PUT("/:endpoint_id", g.Admin(), h.UpdateMCPEndpoint)
+ grp.DELETE("/:endpoint_id", g.Admin(), h.DeleteMCPEndpoint)
+ grp.POST("/:endpoint_id/rotate-token", g.Admin(), h.RotateMCPEndpointToken)
+}
+
+// RegisterMCPServerRoutes mounts the public MCP server surface at
+// /mcp/:endpoint_id. It carries its own bearer-token auth and is registered
+// before the global Auth middleware, like the embed public routes.
+func RegisterMCPServerRoutes(
+ r *gin.Engine,
+ srv *mcpserver.Server,
+ endpointService interfaces.MCPEndpointService,
+ tenantService interfaces.TenantService,
+) {
+ if srv == nil || endpointService == nil {
+ return
+ }
+ h := gin.WrapH(srv.Handler())
+ auth := middleware.MCPEndpointAuth(endpointService, tenantService)
+ for _, method := range []string{http.MethodPost, http.MethodGet, http.MethodDelete} {
+ r.Handle(method, handler.MCPEndpointPath+":endpoint_id", auth, h)
+ }
+}
diff --git a/internal/router/routes_mcp_endpoint_test.go b/internal/router/routes_mcp_endpoint_test.go
new file mode 100644
index 000000000..70c43147f
--- /dev/null
+++ b/internal/router/routes_mcp_endpoint_test.go
@@ -0,0 +1,77 @@
+package router
+
+import (
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/handler"
+ "github.com/Tencent/WeKnora/internal/mcpserver"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+// TestMCPEndpointRoutesDeclareValidAPIKeyPolicies guards the startup
+// self-check for the MCP endpoint management routes: every declared API-key
+// policy must resolve to a registered route.
+func TestMCPEndpointRoutesDeclareValidAPIKeyPolicies(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ v1 := engine.Group("/api/v1")
+ g := &rbacGuards{}
+ RegisterMCPEndpointRoutes(v1, handler.NewMCPEndpointHandler(nil), g)
+ g.assertAPIKeyPoliciesMatchRoutes(engine)
+
+ routes := map[string]bool{}
+ for _, r := range engine.Routes() {
+ routes[r.Method+" "+r.Path] = true
+ }
+ for _, want := range []string{
+ "GET /api/v1/mcp-endpoints",
+ "GET /api/v1/mcp-endpoints/tools",
+ "POST /api/v1/mcp-endpoints",
+ "PUT /api/v1/mcp-endpoints/:endpoint_id",
+ "DELETE /api/v1/mcp-endpoints/:endpoint_id",
+ "POST /api/v1/mcp-endpoints/:endpoint_id/rotate-token",
+ } {
+ if !routes[want] {
+ t.Errorf("route %s not registered", want)
+ }
+ }
+}
+
+type stubMCPEndpointServiceForRoutes struct {
+ interfaces.MCPEndpointService
+}
+
+// TestMCPServerRoutesAreMountedAndReported guards the public MCP surface:
+// the transport must be reachable on every Streamable HTTP method and the
+// deployment capability must flip on only when all three collaborators are
+// injected, mirroring RegisterMCPServerRoutes' nil guard.
+func TestMCPServerRoutesAreMountedAndReported(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ srv := mcpserver.NewServer(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ RegisterMCPServerRoutes(engine, srv, &stubMCPEndpointServiceForRoutes{}, nil)
+
+ routes := map[string]bool{}
+ for _, r := range engine.Routes() {
+ routes[r.Method+" "+r.Path] = true
+ }
+ for _, method := range []string{"POST", "GET", "DELETE"} {
+ if !routes[method+" /mcp/:endpoint_id"] {
+ t.Errorf("%s /mcp/:endpoint_id not registered", method)
+ }
+ }
+
+ params := RouterParams{
+ MCPEndpointHandler: handler.NewMCPEndpointHandler(nil),
+ MCPEndpointService: &stubMCPEndpointServiceForRoutes{},
+ MCPServer: srv,
+ }
+ if !deploymentCapabilitiesFromRouter(params).Capabilities["integrations.mcpserver"].Supported {
+ t.Fatal("integrations.mcpserver must be reported when the MCP server is wired")
+ }
+ params.MCPServer = nil
+ if deploymentCapabilitiesFromRouter(params).Capabilities["integrations.mcpserver"].Supported {
+ t.Fatal("integrations.mcpserver must be off without the MCP server")
+ }
+}
diff --git a/internal/types/const.go b/internal/types/const.go
index 3b74d6d70..c9fdeece0 100644
--- a/internal/types/const.go
+++ b/internal/types/const.go
@@ -69,6 +69,10 @@ const (
// every context key, and middleware imports this package, so a key
// declared there could only be referred to by its raw string value.
EmbedChannelContextKey ContextKey = "EmbedChannel"
+ // MCPEndpointContextKey stores the authenticated *MCPEndpoint on the
+ // request context of a call arriving on the workspace MCP server surface.
+ // Declared here for the same reason as EmbedChannelContextKey.
+ MCPEndpointContextKey ContextKey = "MCPEndpoint"
// LangfuseTraceContextKey carries the active Langfuse *Trace across the
// request lifecycle. Defined here (not inside the langfuse package) so
// that logger.CloneContext can preserve it without importing langfuse.
diff --git a/internal/types/context_clone.go b/internal/types/context_clone.go
index 258d547b9..cda291082 100644
--- a/internal/types/context_clone.go
+++ b/internal/types/context_clone.go
@@ -115,6 +115,9 @@ var contextCloneAcrossDetach = map[ContextKey]bool{
// request context inside the embed handler that authenticated it; nothing
// downstream of a detach reads it.
EmbedChannelContextKey: false,
+ // The authenticated MCP endpoint. Read only by the MCP tool handlers on
+ // the request context that authenticated it.
+ MCPEndpointContextKey: false,
}
// ContextKeysClonedAcrossDetach returns the keys logger.CloneContext carries
diff --git a/internal/types/interfaces/mcp_endpoint.go b/internal/types/interfaces/mcp_endpoint.go
new file mode 100644
index 000000000..72db14856
--- /dev/null
+++ b/internal/types/interfaces/mcp_endpoint.go
@@ -0,0 +1,48 @@
+package interfaces
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// MCPEndpointRepository persists workspace MCP endpoints.
+type MCPEndpointRepository interface {
+ Create(ctx context.Context, ep *types.MCPEndpoint) error
+ GetByID(ctx context.Context, id string) (*types.MCPEndpoint, error)
+ GetByTokenHash(ctx context.Context, tokenHash string) (*types.MCPEndpoint, error)
+ ListByTenant(ctx context.Context, tenantID uint64) ([]*types.MCPEndpoint, error)
+ Update(ctx context.Context, ep *types.MCPEndpoint) error
+ Delete(ctx context.Context, tenantID uint64, id string) error
+ TouchLastUsed(ctx context.Context, id string) error
+}
+
+// MCPEndpointUpdate carries the optional fields of an endpoint update. Nil
+// means "leave unchanged" so a partial PUT does not reset a field.
+type MCPEndpointUpdate struct {
+ Name *string
+ Description *string
+ Enabled *bool
+ KnowledgeBaseIDs *[]string
+ Tools *[]string
+ DefaultAgentID *string
+ RateLimitPerMinute *int
+}
+
+// MCPEndpointService manages the lifecycle of workspace MCP endpoints and
+// resolves bearer tokens for the MCP server surface.
+type MCPEndpointService interface {
+ // Create stores a new endpoint and returns it together with the one-time
+ // plaintext token.
+ Create(ctx context.Context, tenantID uint64, ep *types.MCPEndpoint) (*types.MCPEndpoint, string, error)
+ Get(ctx context.Context, tenantID uint64, id string) (*types.MCPEndpoint, error)
+ List(ctx context.Context, tenantID uint64) ([]*types.MCPEndpoint, error)
+ Update(ctx context.Context, tenantID uint64, id string, upd MCPEndpointUpdate) (*types.MCPEndpoint, error)
+ Delete(ctx context.Context, tenantID uint64, id string) error
+ // RotateToken replaces the bearer token and returns the new plaintext.
+ RotateToken(ctx context.Context, tenantID uint64, id string) (*types.MCPEndpoint, string, error)
+ // Authenticate resolves a bearer token presented on the MCP surface to an
+ // enabled endpoint whose ID matches. It returns ErrMCPEndpointNotFound or
+ // ErrMCPEndpointDisabled style sentinels on failure.
+ Authenticate(ctx context.Context, endpointID, token string) (*types.MCPEndpoint, error)
+}
diff --git a/internal/types/mcp_endpoint.go b/internal/types/mcp_endpoint.go
new file mode 100644
index 000000000..19040427e
--- /dev/null
+++ b/internal/types/mcp_endpoint.go
@@ -0,0 +1,116 @@
+package types
+
+import (
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// MCPEndpoint is one workspace-owned MCP server surface that external MCP
+// clients (Claude Desktop, Cursor, VS Code Copilot, ...) can connect to over
+// Streamable HTTP. A workspace may publish any number of endpoints; each one
+// carries its own bearer token, knowledge-base scope and tool allowlist, so a
+// single WeKnora deployment can serve several narrowly scoped MCP servers
+// without running a separate process per workspace.
+//
+// The endpoint is the unit of trust: everything a connected client may do is
+// derived from this row (see MCPEndpointScope), and the token authenticates
+// the endpoint rather than a person.
+type MCPEndpoint struct {
+ ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
+ TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_mcp_endpoints_tenant"`
+ Name string `json:"name" gorm:"type:varchar(255);not null;default:''"`
+ Description string `json:"description" gorm:"type:text;not null;default:''"`
+ Enabled bool `json:"enabled" gorm:"not null;default:true"`
+ // TokenHash is the SHA-256 hex digest of the bearer token. The plaintext
+ // is shown once on create/rotate and never stored, mirroring
+ // TenantAPIKey.KeyHash rather than the plaintext embed publish token.
+ TokenHash string `json:"-" gorm:"type:varchar(64);not null;default:'';uniqueIndex:idx_mcp_endpoints_token_hash"`
+ // TokenHint is the first few characters of the token so the UI can show
+ // "mcp_ab12…" next to an endpoint without revealing the secret.
+ TokenHint string `json:"token_hint" gorm:"type:varchar(16);not null;default:''"`
+ // KnowledgeBaseIDs bounds every knowledge-facing tool. Empty means every
+ // knowledge base the workspace owns or has been granted at call time.
+ KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
+ // Tools is the allowlist of MCP tool names this endpoint exposes. Names
+ // must come from the MCP endpoint tool catalog; unknown names are dropped
+ // on write.
+ Tools StringArray `json:"tools" gorm:"type:jsonb;not null;default:'[]'"`
+ // DefaultAgentID is the agent used by the ask tool when the caller does
+ // not name one. Empty falls back to the workspace's builtin agent.
+ DefaultAgentID string `json:"default_agent_id" gorm:"type:varchar(36);not null;default:''"`
+ RateLimitPerMinute int `json:"rate_limit_per_minute" gorm:"not null;default:60"`
+ LastUsedAt *time.Time `json:"last_used_at,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
+}
+
+// TableName returns the storage table.
+func (MCPEndpoint) TableName() string { return "mcp_endpoints" }
+
+// DefaultMCPEndpointRateLimitPerMinute bounds tool calls per endpoint per
+// minute when the row does not say otherwise.
+const DefaultMCPEndpointRateLimitPerMinute = 60
+
+// MCPEndpointTokenPrefix distinguishes endpoint tokens from tenant API keys
+// (sk-) and embed publish tokens (em_) at a glance.
+const MCPEndpointTokenPrefix = "mcp_"
+
+// BeforeCreate assigns the id and fills defaults before insert.
+func (e *MCPEndpoint) BeforeCreate(_ *gorm.DB) error {
+ if e.ID == "" {
+ e.ID = uuid.New().String()
+ }
+ if e.RateLimitPerMinute <= 0 {
+ e.RateLimitPerMinute = DefaultMCPEndpointRateLimitPerMinute
+ }
+ if e.KnowledgeBaseIDs == nil {
+ e.KnowledgeBaseIDs = StringArray{}
+ }
+ if e.Tools == nil {
+ e.Tools = StringArray{}
+ }
+ return nil
+}
+
+// HasTool reports whether the endpoint exposes the named tool.
+func (e *MCPEndpoint) HasTool(name string) bool {
+ if e == nil {
+ return false
+ }
+ name = strings.TrimSpace(name)
+ for _, t := range e.Tools {
+ if t == name {
+ return true
+ }
+ }
+ return false
+}
+
+// RestrictsKnowledgeBases reports whether the endpoint pins an explicit
+// knowledge-base allowlist rather than inheriting the whole workspace.
+func (e *MCPEndpoint) RestrictsKnowledgeBases() bool {
+ return e != nil && len(e.KnowledgeBaseIDs) > 0
+}
+
+// AllowsKnowledgeBase reports whether kbID is inside the endpoint scope. An
+// endpoint without an allowlist admits every knowledge base; ownership is
+// still checked by the knowledge services.
+func (e *MCPEndpoint) AllowsKnowledgeBase(kbID string) bool {
+ if e == nil {
+ return false
+ }
+ if len(e.KnowledgeBaseIDs) == 0 {
+ return true
+ }
+ kbID = strings.TrimSpace(kbID)
+ for _, id := range e.KnowledgeBaseIDs {
+ if id == kbID {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/types/mcp_endpoint_tools.go b/internal/types/mcp_endpoint_tools.go
new file mode 100644
index 000000000..3f68e6da3
--- /dev/null
+++ b/internal/types/mcp_endpoint_tools.go
@@ -0,0 +1,182 @@
+package types
+
+import "strings"
+
+// MCPEndpointToolGroup partitions the endpoint tool catalog by the kind of
+// access a tool needs. Groups map onto tenant API key capabilities so the
+// same route/scope checks that guard the REST API also bound MCP tools.
+type MCPEndpointToolGroup string
+
+// Tool groups in display order.
+const (
+ MCPEndpointToolGroupRetrieve MCPEndpointToolGroup = "retrieve"
+ MCPEndpointToolGroupChat MCPEndpointToolGroup = "chat"
+ MCPEndpointToolGroupWiki MCPEndpointToolGroup = "wiki"
+ MCPEndpointToolGroupIngest MCPEndpointToolGroup = "ingest"
+)
+
+// MCP endpoint tool names. These are the names external MCP clients see.
+// They intentionally differ from the agent-internal tool names where the
+// external contract is simpler (one query, server-side session handling).
+const (
+ MCPEndpointToolListKnowledgeBases = "list_knowledge_bases"
+ MCPEndpointToolSearchKnowledge = "search_knowledge"
+ MCPEndpointToolGrepChunks = "grep_chunks"
+ MCPEndpointToolListDocuments = "list_documents"
+ MCPEndpointToolReadDocument = "read_document"
+ MCPEndpointToolAsk = "ask"
+ MCPEndpointToolWikiSearch = "wiki_search"
+ MCPEndpointToolWikiReadPage = "wiki_read_page"
+ MCPEndpointToolWikiIndex = "wiki_index"
+ MCPEndpointToolAddDocument = "add_document"
+ MCPEndpointToolUpdateDocument = "update_document"
+ MCPEndpointToolDeleteDocument = "delete_document"
+)
+
+// MCPEndpointToolDefinition is the settings-facing description of one tool.
+// Label and Description are i18n keys resolved by the frontend.
+type MCPEndpointToolDefinition struct {
+ Name string `json:"name"`
+ Group MCPEndpointToolGroup `json:"group"`
+ // Destructive marks tools that mutate or delete workspace content; the UI
+ // leaves them unchecked by default and the server requires the ingest
+ // capability for them.
+ Destructive bool `json:"destructive"`
+}
+
+// mcpEndpointToolCatalog is the ordered catalog. Order is the display order.
+var mcpEndpointToolCatalog = []MCPEndpointToolDefinition{
+ {Name: MCPEndpointToolListKnowledgeBases, Group: MCPEndpointToolGroupRetrieve},
+ {Name: MCPEndpointToolSearchKnowledge, Group: MCPEndpointToolGroupRetrieve},
+ {Name: MCPEndpointToolGrepChunks, Group: MCPEndpointToolGroupRetrieve},
+ {Name: MCPEndpointToolListDocuments, Group: MCPEndpointToolGroupRetrieve},
+ {Name: MCPEndpointToolReadDocument, Group: MCPEndpointToolGroupRetrieve},
+ {Name: MCPEndpointToolAsk, Group: MCPEndpointToolGroupChat},
+ {Name: MCPEndpointToolWikiSearch, Group: MCPEndpointToolGroupWiki},
+ {Name: MCPEndpointToolWikiReadPage, Group: MCPEndpointToolGroupWiki},
+ {Name: MCPEndpointToolWikiIndex, Group: MCPEndpointToolGroupWiki},
+ {Name: MCPEndpointToolAddDocument, Group: MCPEndpointToolGroupIngest, Destructive: true},
+ {Name: MCPEndpointToolUpdateDocument, Group: MCPEndpointToolGroupIngest, Destructive: true},
+ {Name: MCPEndpointToolDeleteDocument, Group: MCPEndpointToolGroupIngest, Destructive: true},
+}
+
+// MCPEndpointToolCatalog returns a copy of the ordered tool catalog.
+func MCPEndpointToolCatalog() []MCPEndpointToolDefinition {
+ out := make([]MCPEndpointToolDefinition, len(mcpEndpointToolCatalog))
+ copy(out, mcpEndpointToolCatalog)
+ return out
+}
+
+// MCPEndpointToolGroups returns the groups in display order.
+func MCPEndpointToolGroups() []MCPEndpointToolGroup {
+ return []MCPEndpointToolGroup{
+ MCPEndpointToolGroupRetrieve,
+ MCPEndpointToolGroupChat,
+ MCPEndpointToolGroupWiki,
+ MCPEndpointToolGroupIngest,
+ }
+}
+
+// DefaultMCPEndpointTools is the allowlist a new endpoint starts with: every
+// read-only tool, nothing that writes.
+func DefaultMCPEndpointTools() []string {
+ out := make([]string, 0, len(mcpEndpointToolCatalog))
+ for _, def := range mcpEndpointToolCatalog {
+ if !def.Destructive {
+ out = append(out, def.Name)
+ }
+ }
+ return out
+}
+
+// LookupMCPEndpointTool returns the catalog entry for name.
+func LookupMCPEndpointTool(name string) (MCPEndpointToolDefinition, bool) {
+ name = strings.TrimSpace(name)
+ for _, def := range mcpEndpointToolCatalog {
+ if def.Name == name {
+ return def, true
+ }
+ }
+ return MCPEndpointToolDefinition{}, false
+}
+
+// NormalizeMCPEndpointTools drops unknown and duplicate names and returns
+// the survivors in catalog order so the stored allowlist is canonical.
+func NormalizeMCPEndpointTools(in []string) []string {
+ wanted := map[string]struct{}{}
+ for _, name := range in {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ continue
+ }
+ wanted[name] = struct{}{}
+ }
+ out := make([]string, 0, len(wanted))
+ for _, def := range mcpEndpointToolCatalog {
+ if _, ok := wanted[def.Name]; ok {
+ out = append(out, def.Name)
+ }
+ }
+ return out
+}
+
+// MCPEndpointCapabilitiesForTools derives the tenant API key capabilities an
+// endpoint needs so its calls pass the same scope checks as a scoped API key.
+func MCPEndpointCapabilitiesForTools(tools []string) []string {
+ groups := map[MCPEndpointToolGroup]bool{}
+ for _, name := range tools {
+ if def, ok := LookupMCPEndpointTool(name); ok {
+ groups[def.Group] = true
+ }
+ }
+ caps := []string{}
+ if groups[MCPEndpointToolGroupRetrieve] || groups[MCPEndpointToolGroupWiki] || groups[MCPEndpointToolGroupChat] {
+ caps = append(caps, string(APIKeyCapabilityRetrieve))
+ }
+ if groups[MCPEndpointToolGroupChat] {
+ caps = append(caps, string(APIKeyCapabilityChat), string(APIKeyCapabilityReadAgents))
+ }
+ if groups[MCPEndpointToolGroupIngest] {
+ caps = append(caps, string(APIKeyCapabilityIngest))
+ }
+ return caps
+}
+
+// MCPEndpointScope builds the API-key style scope that the MCP server
+// attaches to every call on this endpoint, so downstream services apply the
+// existing knowledge-base and capability checks unchanged.
+func MCPEndpointScope(ep *MCPEndpoint) TenantAPIKeyScope {
+ if ep == nil {
+ return TenantAPIKeyScope{}
+ }
+ kbIDs := StringArray{}
+ if len(ep.KnowledgeBaseIDs) > 0 {
+ kbIDs = append(kbIDs, ep.KnowledgeBaseIDs...)
+ }
+ return TenantAPIKeyScope{
+ ScopeType: APIKeyScopeTenant,
+ FullAccess: false,
+ KnowledgeBaseIDs: kbIDs,
+ Capabilities: StringArray(MCPEndpointCapabilitiesForTools(ep.Tools)),
+ }
+}
+
+// MCPEndpointAgentAllowed reports whether an endpoint of tenantID may run
+// agent for the ask tool. Tenant-owned agents qualify; builtins qualify only
+// when they are user-facing (listed by GetBuiltinAgentIDs). Internal builtins
+// such as the wiki fixer and the skill installer stay unreachable because
+// they ship write and shell tools that the endpoint allowlist never covers.
+func MCPEndpointAgentAllowed(agent *CustomAgent, tenantID uint64) bool {
+ if agent == nil {
+ return false
+ }
+ if agent.IsBuiltin || IsBuiltinAgentID(agent.ID) {
+ for _, id := range GetBuiltinAgentIDs() {
+ if id == agent.ID {
+ return true
+ }
+ }
+ return false
+ }
+ return agent.TenantID == tenantID
+}
diff --git a/internal/types/mcp_endpoint_tools_test.go b/internal/types/mcp_endpoint_tools_test.go
new file mode 100644
index 000000000..1b3cf96c8
--- /dev/null
+++ b/internal/types/mcp_endpoint_tools_test.go
@@ -0,0 +1,76 @@
+package types
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestNormalizeMCPEndpointToolsDropsUnknownAndOrders(t *testing.T) {
+ got := NormalizeMCPEndpointTools([]string{
+ " ask ", "bogus", MCPEndpointToolSearchKnowledge, MCPEndpointToolAsk, "", MCPEndpointToolListKnowledgeBases,
+ })
+ want := []string{MCPEndpointToolListKnowledgeBases, MCPEndpointToolSearchKnowledge, MCPEndpointToolAsk}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+}
+
+func TestDefaultMCPEndpointToolsExcludesDestructive(t *testing.T) {
+ for _, name := range DefaultMCPEndpointTools() {
+ def, ok := LookupMCPEndpointTool(name)
+ if !ok {
+ t.Fatalf("default tool %q missing from catalog", name)
+ }
+ if def.Destructive {
+ t.Fatalf("default tool %q must not be destructive", name)
+ }
+ }
+ if _, ok := LookupMCPEndpointTool(MCPEndpointToolDeleteDocument); !ok {
+ t.Fatal("delete_document must be in the catalog")
+ }
+}
+
+func TestMCPEndpointCapabilitiesForTools(t *testing.T) {
+ cases := []struct {
+ name string
+ tools []string
+ want []string
+ }{
+ {"retrieve only", []string{MCPEndpointToolSearchKnowledge}, []string{"retrieve"}},
+ {"wiki only", []string{MCPEndpointToolWikiIndex}, []string{"retrieve"}},
+ {"ask", []string{MCPEndpointToolAsk}, []string{"retrieve", "chat", "read_agents"}},
+ {"ingest", []string{MCPEndpointToolAddDocument}, []string{"ingest"}},
+ {"none", nil, []string{}},
+ }
+ for _, tc := range cases {
+ if got := MCPEndpointCapabilitiesForTools(tc.tools); !reflect.DeepEqual(got, tc.want) {
+ t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestMCPEndpointScopeMirrorsEndpoint(t *testing.T) {
+ ep := &MCPEndpoint{
+ KnowledgeBaseIDs: StringArray{"kb-1", "kb-2"},
+ Tools: StringArray{MCPEndpointToolAsk, MCPEndpointToolDeleteDocument},
+ }
+ scope := MCPEndpointScope(ep)
+ if scope.FullAccess {
+ t.Fatal("endpoint scope must never be full access")
+ }
+ if !scope.AllowsKnowledgeBase("kb-1") || scope.AllowsKnowledgeBase("kb-3") {
+ t.Fatal("knowledge base allowlist not mirrored")
+ }
+ if !scope.HasCapability(APIKeyCapabilityChat) || !scope.HasCapability(APIKeyCapabilityIngest) {
+ t.Fatal("capabilities not derived from tools")
+ }
+ if MCPEndpointScope(nil).HasCapability(APIKeyCapabilityRetrieve) {
+ t.Fatal("nil endpoint must yield an empty scope")
+ }
+ if !ep.HasTool("ask") || ep.HasTool("search_knowledge") {
+ t.Fatal("HasTool mismatch")
+ }
+ if !(&MCPEndpoint{}).AllowsKnowledgeBase("anything") {
+ t.Fatal("unrestricted endpoint must allow any knowledge base")
+ }
+}
diff --git a/internal/types/principal.go b/internal/types/principal.go
index cf2087c9d..263e19ea1 100644
--- a/internal/types/principal.go
+++ b/internal/types/principal.go
@@ -15,6 +15,7 @@ const (
PrincipalEmbedChannel = "embed_channel"
PrincipalEmbedSession = "embed_session"
PrincipalEmbedVisitor = "embed_visitor"
+ PrincipalMCPEndpoint = "mcp_endpoint"
)
// EmbedVisitorHeader is sent by the embed widget to identify a browser visitor
@@ -107,6 +108,15 @@ func EmbedVisitorIDFromContext(ctx context.Context) string {
}
// EmbedSessionPrincipal identifies a single embed visitor chat session.
+// MCPEndpointPrincipal identifies calls made through a workspace MCP
+// endpoint. Sessions and messages created by the ask tool are owned by it.
+func MCPEndpointPrincipal(tenantID uint64, endpointID string) Principal {
+ return Principal{
+ Type: PrincipalMCPEndpoint,
+ ID: fmt.Sprintf("%d:%s", tenantID, endpointID),
+ }
+}
+
func EmbedSessionPrincipal(tenantID uint64, channelID, sessionID string) Principal {
return Principal{
Type: PrincipalEmbedSession,
diff --git a/mcp-server/README.md b/mcp-server/README.md
index a7a64dd8f..4580cfa4b 100644
--- a/mcp-server/README.md
+++ b/mcp-server/README.md
@@ -1,5 +1,11 @@
# WeKnora MCP Server
+> **⚠️ 已弃用(Deprecated)**
+>
+> WeKnora 现已内置 MCP Server:在「设置 → 发布与集成 → MCP Server」中为空间创建端点即可,支持多个端点、按端点选择知识库范围和工具,客户端通过 Streamable HTTP 直接连接 `/mcp/<endpoint_id>`,无需再部署本目录的 Python 进程。本目录仅为兼容旧部署保留,后续版本将移除。
+>
+> WeKnora now ships a built-in MCP server: create endpoints under "Settings → Publish & Integrations → MCP Server", each with its own token, knowledge-base scope and tool list, and connect clients to `/mcp/<endpoint_id>` over Streamable HTTP. This Python package is kept only for existing deployments and will be removed in a future release.
+
这是一个 Model Context Protocol (MCP) 服务器,提供对 WeKnora 知识管理 API 的访问。
## 快速开始
diff --git a/migrations/sqlite/000022_mcp_endpoints.down.sql b/migrations/sqlite/000022_mcp_endpoints.down.sql
new file mode 100644
index 000000000..efa1146c2
--- /dev/null
+++ b/migrations/sqlite/000022_mcp_endpoints.down.sql
@@ -0,0 +1,4 @@
+DROP INDEX IF EXISTS idx_mcp_endpoints_deleted;
+DROP INDEX IF EXISTS idx_mcp_endpoints_token_hash;
+DROP INDEX IF EXISTS idx_mcp_endpoints_tenant;
+DROP TABLE IF EXISTS mcp_endpoints;
diff --git a/migrations/sqlite/000022_mcp_endpoints.up.sql b/migrations/sqlite/000022_mcp_endpoints.up.sql
new file mode 100644
index 000000000..ac1b53ee6
--- /dev/null
+++ b/migrations/sqlite/000022_mcp_endpoints.up.sql
@@ -0,0 +1,27 @@
+-- Mirrors versioned migration 000102_mcp_endpoints:
+-- workspace-published MCP server endpoints with per-endpoint token, KB scope
+-- and tool allowlist.
+
+CREATE TABLE IF NOT EXISTS mcp_endpoints (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL DEFAULT '',
+ description TEXT NOT NULL DEFAULT '',
+ enabled INTEGER NOT NULL DEFAULT 1,
+ token_hash VARCHAR(64) NOT NULL DEFAULT '',
+ token_hint VARCHAR(16) NOT NULL DEFAULT '',
+ knowledge_base_ids TEXT NOT NULL DEFAULT '[]',
+ tools TEXT NOT NULL DEFAULT '[]',
+ default_agent_id VARCHAR(36) NOT NULL DEFAULT '',
+ rate_limit_per_minute INTEGER NOT NULL DEFAULT 60,
+ last_used_at DATETIME,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ deleted_at DATETIME
+);
+
+CREATE INDEX IF NOT EXISTS idx_mcp_endpoints_tenant ON mcp_endpoints (tenant_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_mcp_endpoints_token_hash
+ ON mcp_endpoints (token_hash)
+ WHERE token_hash != '' AND deleted_at IS NULL;
+CREATE INDEX IF NOT EXISTS idx_mcp_endpoints_deleted ON mcp_endpoints (deleted_at) WHERE deleted_at IS NOT NULL;
diff --git a/migrations/versioned/000102_mcp_endpoints.down.sql b/migrations/versioned/000102_mcp_endpoints.down.sql
new file mode 100644
index 000000000..efa1146c2
--- /dev/null
+++ b/migrations/versioned/000102_mcp_endpoints.down.sql
@@ -0,0 +1,4 @@
+DROP INDEX IF EXISTS idx_mcp_endpoints_deleted;
+DROP INDEX IF EXISTS idx_mcp_endpoints_token_hash;
+DROP INDEX IF EXISTS idx_mcp_endpoints_tenant;
+DROP TABLE IF EXISTS mcp_endpoints;
diff --git a/migrations/versioned/000102_mcp_endpoints.up.sql b/migrations/versioned/000102_mcp_endpoints.up.sql
new file mode 100644
index 000000000..8a3a9f8dc
--- /dev/null
+++ b/migrations/versioned/000102_mcp_endpoints.up.sql
@@ -0,0 +1,35 @@
+-- Migration: 000102_mcp_endpoints
+-- Workspace-published MCP server endpoints: each row is one bearer-token
+-- protected MCP surface with its own knowledge-base scope and tool allowlist.
+DO $$ BEGIN RAISE NOTICE '[Migration 000102] Creating mcp_endpoints table'; END $$;
+
+CREATE TABLE IF NOT EXISTS mcp_endpoints (
+ id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
+ tenant_id BIGINT NOT NULL,
+ name VARCHAR(255) NOT NULL DEFAULT '',
+ description TEXT NOT NULL DEFAULT '',
+ enabled BOOLEAN NOT NULL DEFAULT true,
+ token_hash VARCHAR(64) NOT NULL DEFAULT '',
+ token_hint VARCHAR(16) NOT NULL DEFAULT '',
+ knowledge_base_ids JSONB NOT NULL DEFAULT '[]',
+ tools JSONB NOT NULL DEFAULT '[]',
+ default_agent_id VARCHAR(36) NOT NULL DEFAULT '',
+ rate_limit_per_minute INTEGER NOT NULL DEFAULT 60,
+ last_used_at TIMESTAMP WITH TIME ZONE,
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ deleted_at TIMESTAMP WITH TIME ZONE
+);
+
+CREATE INDEX IF NOT EXISTS idx_mcp_endpoints_tenant ON mcp_endpoints (tenant_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_mcp_endpoints_token_hash
+ ON mcp_endpoints (token_hash)
+ WHERE token_hash <> '' AND deleted_at IS NULL;
+CREATE INDEX IF NOT EXISTS idx_mcp_endpoints_deleted ON mcp_endpoints (deleted_at) WHERE deleted_at IS NOT NULL;
+
+COMMENT ON TABLE mcp_endpoints IS 'Workspace-published MCP server endpoints consumed by external MCP clients';
+COMMENT ON COLUMN mcp_endpoints.token_hash IS 'SHA-256 hex of the bearer token (mcp_ prefix); plaintext is shown once and never stored';
+COMMENT ON COLUMN mcp_endpoints.token_hint IS 'Leading characters of the token for display only';
+COMMENT ON COLUMN mcp_endpoints.knowledge_base_ids IS 'Knowledge-base allowlist; empty array means every workspace knowledge base';
+COMMENT ON COLUMN mcp_endpoints.tools IS 'Allowlisted MCP tool names from the endpoint tool catalog';
+COMMENT ON COLUMN mcp_endpoints.default_agent_id IS 'Agent used by the ask tool when the caller does not name one';
diff --git a/website-docs/03-features/08-mcp.md b/website-docs/03-features/08-mcp.md
index ba2602110..ac4864b2e 100644
--- a/website-docs/03-features/08-mcp.md
+++ b/website-docs/03-features/08-mcp.md
@@ -3,7 +3,7 @@
MCP 用于智能体与外部工具之间的连接。WeKnora 支持接入外部 MCP 服务,也提供独立 MCP Server 供其他客户端调用:
1. **WeKnora 作为 MCP 客户端**:在「MCP 服务」设置中接入任意外部 MCP server(SSE / Streamable HTTP),其工具自动注册进 Agent 的工具箱,供 Agent 在对话中调用。支持 API Key / Bearer / OAuth 2.0(含动态客户端注册与 PKCE)三种认证策略、按工具粒度的人工审批,以及会话内(in-conversation)OAuth 授权。
-2. **WeKnora 作为 MCP Server**:仓库 `mcp-server/` 目录提供一个独立的 Python MCP server(PyPI 包 `tencent-weknora-mcp`,入口命令 `weknora-mcp-server`),把 WeKnora 的知识库、检索、会话、Agent 问答、Wiki 等 REST API 封装成 31 个 MCP 工具,供 Claude Desktop、VS Code Copilot 等外部 MCP 客户端使用。
+2. **WeKnora 作为 MCP Server**:在「发布与集成 → MCP Server」中为当前空间创建一个或多个 MCP 端点,每个端点有独立的令牌、知识库范围和工具清单,Claude Desktop、Cursor、Claude Code、VS Code Copilot 等 MCP 客户端通过 Streamable HTTP 直接连接,无需额外部署进程。仓库 `mcp-server/` 目录下的 Python 服务是旧方案,已标记弃用。
接入外部服务可扩展 WeKnora 智能体的工具;运行 WeKnora MCP Server 可让外部客户端使用知识库检索、问答和管理能力。
@@ -26,20 +26,31 @@ OAuth 服务按调用者分别授权。工具需要审批时,在对话中检
## 供外部客户端调用
-在外部客户端所在环境安装 `tencent-weknora-mcp`,配置 WeKnora API 地址与 API Key,再启动 `weknora-mcp-server`。客户端可调用知识库、检索、会话和 Wiki 等 31 个工具,范围受 API Key 权限约束。
+在「设置 → 发布与集成 → MCP Server」新建端点:填写名称、选择可访问的知识库(留空为全部)、勾选要暴露的工具,需要问答时再指定默认 Agent。创建后会一次性展示令牌和地址 `/mcp/<endpoint_id>`,页面同时给出 Cursor / VS Code / Claude Desktop 的 `mcpServers` 配置、Claude Code 的一行命令,以及仅支持 stdio 的客户端通过 `mcp-remote` 桥接的写法。
-安装命令、环境变量、传输模式和客户端配置示例见下方 MCP Server 参考。
+一个空间可以创建多个端点。例如给客服团队一个只开检索和问答、只看两个知识库的端点,给内容团队另一个开了写入工具的端点。令牌可随时轮换,端点可随时停用,删除端点后使用它的客户端立即断开。
+
+端点暴露的工具按四组勾选,默认只开只读工具:
+
+| 组 | 工具 | 说明 |
+|---|---|---|
+| 检索与阅读 | `list_knowledge_bases`、`search_knowledge`、`grep_chunks`、`list_documents`、`read_document` | 知识库参数同时接受 ID 或名称;语义搜索与关键词正则搜索分开 |
+| 问答 | `ask` | 只运行端点配置的默认 Agent(客户端不能自选 Agent),服务端自动建会话,返回带引用的完整回答和 `session_id`,续聊时传回即可;不开启联网搜索 |
+| Wiki | `wiki_search`、`wiki_read_page`、`wiki_index` | 只对开启了 Wiki 的知识库生效 |
+| 写入 | `add_document`、`update_document`、`delete_document` | 默认关闭;支持 Markdown 文本或 URL 导入 |
+
+工具实现直接复用 Agent 的原生工具(`internal/agent/tools/`),鉴权复用 API Key 的作用域模型:端点被换算成一把仅含 retrieve / chat / ingest 等能力、限定知识库范围的作用域,所以后端各服务对它的检查与对受限 API Key 完全一致。实现细节见下方内置 MCP Server 参考。
## 接入方式对照 {#两个方向的对照速览}
| 维度 | WeKnora 作为 MCP 客户端 | WeKnora 作为 MCP Server |
|---|---|---|
-| 代码位置 | `internal/mcp/` + handler/service/repository + `internal/agent/tools/` | `mcp-server/`(Python) |
-| 协议库 | `github.com/mark3labs/mcp-go` | `mcp`(官方 Python SDK,2.x 高层 `MCPServer` API) |
-| 传输 | SSE、Streamable HTTP(stdio 因安全禁用) | stdio(默认)、SSE、Streamable HTTP |
-| 认证 | API Key / Bearer / OAuth 2.0(DCR + PKCE,token AES 加密、按 principal 隔离) | 出站 `X-API-Key`(WeKnora API Key);入站网络传输 `MCP_SERVER_AUTH_TOKEN` |
-| 安全控制 | 工具级人工审批、SSRF 校验、不可信输出前缀、DTO 级密钥隔离 | 上传目录白名单、网络传输强制鉴权、SSL 校验默认开启 |
-| 消费者 | WeKnora Agent(对话中自动调用) | Claude Desktop / VS Code Copilot 等任意 MCP 客户端 |
+| 代码位置 | `internal/mcp/` + handler/service/repository + `internal/agent/tools/` | `internal/mcpserver/` + `internal/middleware/mcp_endpoint_auth.go` + `internal/handler/mcp_endpoint.go` |
+| 协议库 | `github.com/mark3labs/mcp-go`(client) | `github.com/mark3labs/mcp-go`(server,Streamable HTTP,无状态模式) |
+| 传输 | SSE、Streamable HTTP(stdio 因安全禁用) | Streamable HTTP;stdio 客户端用 `mcp-remote` 桥接 |
+| 认证 | API Key / Bearer / OAuth 2.0(DCR + PKCE,token AES 加密、按 principal 隔离) | 入站 `Authorization: Bearer mcp_…`,每个端点独立令牌(SHA-256 存储,可轮换) |
+| 安全控制 | 工具级人工审批、SSRF 校验、不可信输出前缀、DTO 级密钥隔离 | 端点级工具白名单(列表与调用双重校验)、知识库范围、每分钟限流、令牌只展示一次 |
+| 消费者 | WeKnora Agent(对话中自动调用) | Claude Desktop / Cursor / Claude Code / VS Code Copilot 等任意 MCP 客户端 |
## 配置与实现参考
@@ -352,7 +363,78 @@ flowchart LR
---
-### MCP Server 参考 {#第二部分-weknora-作为-mcp-server-mcp-server}
+### 内置 MCP Server 参考 {#第二部分-weknora-作为-mcp-server}
+
+#### 数据模型与管理 API
+
+`mcp_endpoints` 表(PostgreSQL 迁移 `000102_mcp_endpoints`,SQLite `000022_mcp_endpoints`)每行一个端点:`tenant_id`、`name`、`enabled`、`token_hash`(SHA-256)、`token_hint`(前缀展示用)、`knowledge_base_ids`(空数组表示空间内全部)、`tools`(白名单)、`default_agent_id`、`rate_limit_per_minute`、`last_used_at`。类型定义在 `internal/types/mcp_endpoint.go`,工具目录在 `internal/types/mcp_endpoint_tools.go`。
+
+管理接口挂在 `/api/v1/mcp-endpoints`,读取需 Viewer,变更需 Admin,API Key 需要 `manage_channels` 能力:
+
+| 方法 | 路径 | 说明 |
+|---|---|---|
+| GET | `/mcp-endpoints` | 列表 |
+| GET | `/mcp-endpoints/tools` | 工具目录(分组、默认勾选) |
+| POST | `/mcp-endpoints` | 创建,响应含一次性 `token` |
+| GET / PUT / DELETE | `/mcp-endpoints/:endpoint_id` | 详情 / 更新 / 删除 |
+| POST | `/mcp-endpoints/:endpoint_id/rotate-token` | 轮换令牌,响应含新 `token` |
+
+#### 请求链路
+
+```mermaid
+flowchart LR
+ C["MCP 客户端"] -->|"POST /mcp/:endpoint_id<br/>Authorization: Bearer mcp_…"| A["MCPEndpointAuth<br/>(internal/middleware)"]
+ A -->|"注入 tenant / principal /<br/>TenantAPIKeyScope / *MCPEndpoint"| S["mcp-go StreamableHTTPServer<br/>(internal/mcpserver)"]
+ S -->|"tools/list"| F["ToolFilter:按端点白名单过滤"]
+ S -->|"tools/call"| G["Guard:白名单 + 限流 + last_used"]
+ G --> T["工具处理器:复用 internal/agent/tools<br/>KnowledgeSearch / GrepChunks / ListChunks / Wiki…"]
+ G --> Q["ask:SessionService.AgentQA / KnowledgeQA<br/>同步收集 final_answer + references"]
+```
+
+- 公开路由 `/mcp/:endpoint_id` 注册在全局 Auth 中间件之前,与 embed 公开路由同级;`MCPEndpointAuth` 解析令牌后通过 `applyAuthSession` 写入租户、合成用户、`mcp_endpoint` principal,以及由端点换算出的 `TenantAPIKeyScope`(`types.MCPEndpointScope`),下游服务据此做知识库范围和能力检查。
+- 全局只有一个 `MCPServer` 实例注册完整工具目录;`WithToolFilter` 按请求上下文里的端点过滤 `tools/list`,`WithToolHandlerMiddleware` 在 `tools/call` 再校验一次白名单并做每端点滑动窗口限流(Redis 优先,本地回退)。
+- 传输使用 `WithStateLess(true)`,任意副本都能处理任意请求,客户端无需保持 `Mcp-Session-Id`。
+- `ask` 工具的会话归属为 `mcp_endpoint:<tenant>:<endpoint>`,续聊时校验 `session_id` 属于同一端点;单次回答上限 4 分钟。
+- 文档级工具(列表、阅读、写入)先用 `access.ResolveKB` 解析权限,再在知识库所属空间下执行,因此组织分享过来的知识库也能读写,且新建文档落在所有者空间。
+
+#### 客户端配置示例
+
+```json
+{
+ "mcpServers": {
+ "weknora-docs": {
+ "url": "https://your-weknora.example.com/mcp/<endpoint_id>",
+ "headers": { "Authorization": "Bearer mcp_xxxxxxxx" }
+ }
+ }
+}
+```
+
+Claude Code:
+
+```bash
+claude mcp add --transport http weknora-docs https://your-weknora.example.com/mcp/<endpoint_id> --header "Authorization: Bearer mcp_xxxxxxxx"
+```
+
+仅支持 stdio 的客户端:
+
+```json
+{
+ "mcpServers": {
+ "weknora-docs": {
+ "command": "npx",
+ "args": ["-y", "mcp-remote", "https://your-weknora.example.com/mcp/<endpoint_id>", "--header", "Authorization: Bearer mcp_xxxxxxxx"]
+ }
+ }
+}
+```
+
+### Python MCP Server 参考(旧版,已弃用) {#第二部分-weknora-作为-mcp-server-mcp-server}
+
+::: warning 已弃用
+`mcp-server/` 下的 Python 服务是内置 MCP Server 之前的方案:每个进程绑定一把 API Key,只能访问一个空间,工具与 REST 接口一一对应。新部署请使用上面的内置 MCP Server;本节仅供仍在使用旧方案的用户参考,后续版本会移除该目录。
+:::
+
`mcp-server/` 是一个独立的 Python 包,PyPI 名 **`tencent-weknora-mcp`**(当前 1.1.1,Python ≥ 3.10,依赖 `mcp>=2,<3`、`requests>=2.31.0`、`starlette`、`uvicorn`),核心实现在 `mcp-server/weknora_mcp_server.py`:`WeKnoraClient` 用 `requests.Session` 携带 `X-API-Key` 调 WeKnora REST API,`MCPServer("weknora-server", version="1.1.1")` 注册工具并通过所选传输对外服务。
diff --git a/website-docs/05-clients/03-go-sdk.md b/website-docs/05-clients/03-go-sdk.md
index 8d4b56c71..4c6dfbaaa 100644
--- a/website-docs/05-clients/03-go-sdk.md
+++ b/website-docs/05-clients/03-go-sdk.md
@@ -291,6 +291,14 @@ kb, err := apiClient.GetKnowledgeBase(ctx, kbID)
| `GetMCPServiceTools` / `GetMCPServiceResources` | 列出 MCP 工具/资源 |
| `ResolveToolApproval` | 处理工具调用审批 |
+### MCP 端点(WeKnora 作为 MCP Server)— `client/mcp_endpoint.go`
+
+| 方法 | 说明 |
+|---|---|
+| `ListMCPEndpoints` / `GetMCPEndpoint` / `CreateMCPEndpoint` / `UpdateMCPEndpoint` / `DeleteMCPEndpoint` | 工作空间对外发布的 MCP 端点 CRUD;创建响应中的 `Token` 只返回一次 |
+| `RotateMCPEndpointToken` | 轮换端点令牌,旧令牌立即失效 |
+| `GetMCPEndpointToolCatalog` | 端点可勾选的工具目录、分组与默认勾选 |
+
### 初始化与模型检测 — `client/initialization.go`
| 方法 | 说明 |