diff --git a/client/mcp_endpoint.go b/client/mcp_endpoint.go new file mode 100644 index 00000000..3b4c5540 --- /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/). + 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 401360e1..ed4fb7a3 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" - } } } } @@ -13204,6 +13487,113 @@ const docTemplate = `{ } } }, + "/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": "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/{session_id}/artifacts": { "get": { "security": [ @@ -13245,6 +13635,74 @@ const docTemplate = `{ } } }, + "/sessions/{session_id}/fork": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "从指定的用户或助手消息处分叉出一个新会话。用户消息:复制其之前的历史并预填该问题;助手消息:复制含该回答在内的历史,从该轮沙箱状态继续。", + "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.ForkSessionRequest" + } + } + ], + "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" + } + }, + "409": { + "description": "源会话正在生成中", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/sessions/{session_id}/messages/{message_id}/artifacts": { "get": { "responses": {} @@ -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 170fab22..9e00f227 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" - } } } } @@ -13197,6 +13480,113 @@ } } }, + "/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": "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/{session_id}/artifacts": { "get": { "security": [ @@ -13238,6 +13628,74 @@ } } }, + "/sessions/{session_id}/fork": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "从指定的用户或助手消息处分叉出一个新会话。用户消息:复制其之前的历史并预填该问题;助手消息:复制含该回答在内的历史,从该轮沙箱状态继续。", + "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.ForkSessionRequest" + } + } + ], + "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" + } + }, + "409": { + "description": "源会话正在生成中", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/sessions/{session_id}/messages/{message_id}/artifacts": { "get": { "responses": {} @@ -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 35975aae..f4c15ebd 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 00000000..c00403b8 --- /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 { + success: boolean + data: T +} + +export function listMcpEndpoints() { + return get>('/api/v1/mcp-endpoints') +} + +export function getMcpEndpointToolCatalog() { + return get>('/api/v1/mcp-endpoints/tools') +} + +export function createMcpEndpoint(data: McpEndpointPayload) { + return post>('/api/v1/mcp-endpoints', data) +} + +export function updateMcpEndpoint(id: string, data: McpEndpointPayload) { + return put>(`/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>(`/api/v1/mcp-endpoints/${id}/rotate-token`, {}) +} diff --git a/frontend/src/config/deploymentCapabilities.ts b/frontend/src/config/deploymentCapabilities.ts index e0b6f7bc..ce7726f5 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 bed068b6..29f4c4b4 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 +
+
+

{{ $t('integrations.mcpserver.title') }}

+

{{ $t('integrations.mcpserver.subtitle') }}

+
+ +
+ @@ -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 00000000..800fc2a9 --- /dev/null +++ b/frontend/src/views/integrations/McpServerIntegrationSettings.vue @@ -0,0 +1,653 @@ + + + + + diff --git a/frontend/src/views/integrations/mcpServerIntegration.test.ts b/frontend/src/views/integrations/mcpServerIntegration.test.ts new file mode 100644 index 00000000..e03f8577 --- /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 00000000..64a29206 --- /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 = '' + +/** + * Derive the public MCP URL from the displayed API base (".../api/v1") and + * the endpoint path ("/mcp/") 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 { + group: string + tools: T[] +} + +/** Group catalog entries in the backend's group order, dropping empty groups. */ +export function groupTools(groups: string[], tools: T[]): GroupedTools[] { + const known = new Set(groups) + const order = [...groups, ...tools.map((t) => t.group).filter((g) => !known.has(g))] + const out: GroupedTools[] = [] + 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[] { + 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 00000000..e383cdb8 --- /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 00000000..53a0ab8b --- /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 00000000..6a066a12 --- /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 caa6a611..16bd7df0 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 ded50b48..6ea1da70 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 9c8d905a..7d8afc46 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 00000000..aea6f078 --- /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 00000000..683f178e --- /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 00000000..cba94504 --- /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 00000000..04165f28 --- /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 00000000..b4cdcabe --- /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 00000000..4bc7f36c --- /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 00000000..658bbad0 --- /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 00000000..bf4aa124 --- /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 00000000..109f40b9 --- /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 00000000..9aabeaf1 --- /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-%s@mcp.local", 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 00000000..1e9f2954 --- /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 aab2f63a..e9a05aba 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 05346e5d..9eb920e3 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 00000000..aa7b622a --- /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 00000000..70c43147 --- /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 3b74d6d7..c9fdeece 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 258d547b..cda29108 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 00000000..72db1485 --- /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 00000000..19040427 --- /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 00000000..3f68e6da --- /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 00000000..1b3cf96c --- /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 cf2087c9..263e19ea 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 a7a64dd8..4580cfa4 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/`,无需再部署本目录的 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/` 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 00000000..efa1146c --- /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 00000000..ac1b53ee --- /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 00000000..efa1146c --- /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 00000000..8a3a9f8d --- /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 ba260211..ac4864b2 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/`,页面同时给出 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
Authorization: Bearer mcp_…"| A["MCPEndpointAuth
(internal/middleware)"] + A -->|"注入 tenant / principal /
TenantAPIKeyScope / *MCPEndpoint"| S["mcp-go StreamableHTTPServer
(internal/mcpserver)"] + S -->|"tools/list"| F["ToolFilter:按端点白名单过滤"] + S -->|"tools/call"| G["Guard:白名单 + 限流 + last_used"] + G --> T["工具处理器:复用 internal/agent/tools
KnowledgeSearch / GrepChunks / ListChunks / Wiki…"] + G --> Q["ask:SessionService.AgentQA / KnowledgeQA
同步收集 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::`,续聊时校验 `session_id` 属于同一端点;单次回答上限 4 分钟。 +- 文档级工具(列表、阅读、写入)先用 `access.ResolveKB` 解析权限,再在知识库所属空间下执行,因此组织分享过来的知识库也能读写,且新建文档落在所有者空间。 + +#### 客户端配置示例 + +```json +{ + "mcpServers": { + "weknora-docs": { + "url": "https://your-weknora.example.com/mcp/", + "headers": { "Authorization": "Bearer mcp_xxxxxxxx" } + } + } +} +``` + +Claude Code: + +```bash +claude mcp add --transport http weknora-docs https://your-weknora.example.com/mcp/ --header "Authorization: Bearer mcp_xxxxxxxx" +``` + +仅支持 stdio 的客户端: + +```json +{ + "mcpServers": { + "weknora-docs": { + "command": "npx", + "args": ["-y", "mcp-remote", "https://your-weknora.example.com/mcp/", "--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 8d4b56c7..4c6dfbaa 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` | 方法 | 说明 |