Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(mcp)!: replace the stale skills with server instructions (#21552)
Vincent Huang047a7c63aaf6
diff --git a/backend/api/mcp/AGENTS.md b/backend/api/mcp/AGENTS.mddeleted file mode 100644index f4d948762c..0000000000--- a/backend/api/mcp/AGENTS.md+++ /dev/null@@ -1,106 +0,0 @@-# MCP Server Skills--This directory contains the Bytebase MCP server implementation with embedded skills that provide step-by-step guides for common tasks.--## Writing Skills--Skills are markdown files in `skills/` that get embedded into the binary and served via the `get_skill` tool.--### File Structure--```-skills/-├── query.md-└── database-change.md-```--### Skill Format--Each skill file must have YAML frontmatter followed by markdown content:--```markdown-----name: skill-name-description: Use when [triggering conditions] - [what it does]------# Skill Title--## Overview--One-liner explaining what this accomplishes.--## Prerequisites--- Required permissions-- What you need to know beforehand--## Workflow--1. **Step name**:- ```- search_api(operationId="Service/Method")- ```- ```- call_api(operationId="Service/Method", body={...})- ```--2. **Next step**:- ...--## Common Errors--| Error | Cause | Fix |-|-------|-------|-----|-| error message | why it happens | how to fix |-```--### Guidelines--1. **Description starts with "Use when..."** - Include triggering conditions and keywords for discoverability--2. **Always include `search_api` before `call_api`** - Claude needs to fetch the schema to know exact field names--3. **Use placeholders consistently**:- - `{project-id}` - project identifier- - `{instance-id}` - instance identifier- - `{database-name}` - database name- - `{sheet-id}` - sheet identifier- - `{plan-id}` - plan identifier--4. **Prefer discovery over hardcoding** - Use `search_api(schema="EnumName")` instead of listing enum values--5. **Note encoding requirements** - e.g., sheet content is base64 encoded--6. **List required permissions** in Prerequisites--7. **Include common errors** to help with troubleshooting--### Adding a New Skill--1. Create `skills/new-skill.md` with frontmatter and content-2. Update `tool_skill.go` to add the skill name to `getSkillDescription`-3. Update `tool_skill_test.go` to include the skill in `TestGetSkillAllSkillsLoadable`-4. Run tests: `go test ./backend/api/mcp/... -run TestGetSkill`--### Testing--```bash-# Run all skill tests-go test -v github.com/bytebase/bytebase/backend/api/mcp -run ^TestGetSkill--# Verify skill loads correctly-go test -v github.com/bytebase/bytebase/backend/api/mcp -run ^TestGetSkillAllSkillsLoadable-```--## Tool Description--When adding new skills, update the tool description in `tool_skill.go`:--```go-const getSkillDescription = `Get step-by-step guides for Bytebase tasks.--**Workflow:** get_skill("task") → search_api(operationId) → call_api(...)--Skills: query, database-change, NEW-SKILL`-```diff --git a/backend/api/mcp/CLAUDE.md b/backend/api/mcp/CLAUDE.mddeleted file mode 100644index 43c994c2d3..0000000000--- a/backend/api/mcp/CLAUDE.md+++ /dev/null@@ -1 +0,0 @@diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.goindex 055a7f3539..563e81c06c 100644--- a/backend/api/mcp/server.go+++ b/backend/api/mcp/server.go@@ -91,7 +91,7 @@ func newServerWithStore(stores serverStore, profile *config.Profile, secret strimcpServer := mcp.NewServer(&mcp.Implementation{Name: "bytebase",Version: profile.Version,- }, nil)+ }, &mcp.ServerOptions{Instructions: serverInstructions})// Load OpenAPI index for API discovery and execution (embedded)openAPIIndex, err := NewOpenAPIIndex()@@ -154,6 +154,7 @@ func newServerWithStore(stores serverStore, profile *config.Profile, secret strimcpServer.AddReceivingMiddleware(negotiateLegacyProtocol)mcpServer.AddReceivingMiddleware(liveRequestMetadata)mcpServer.AddReceivingMiddleware(nameSignedInAccount)+ mcpServer.AddReceivingMiddleware(askInChatWithoutForm)// Pin each session to the identity it was opened with. The SDK captures// TokenInfo.UserID when a session is created and rejects later requests@@ -216,7 +217,21 @@ func nameSignedInAccount(next mcp.MethodHandler) mcp.MethodHandler {// and a panic here would end the process.if initialized, ok := result.(*mcp.InitializeResult); ok && initialized != nil {account := fmt.Sprintf(`This session acts as the Bytebase account %s: every tool call runs with its permissions, and "you" in tool results means it. The user may have other accounts with other emails, such as the client's own sign-in.`, getUserEmail(ctx))- initialized.Instructions = strings.TrimSpace(account + "\n\n" + initialized.Instructions)+ initialized.Instructions = account + "\n\n" + initialized.Instructions+ }+ return result, err+ }+}++// askInChatWithoutForm ends the instructions of a session whose client declared+// no form with askInChatInstructions: query_database then runs a write without+// asking the user (canShowConfirmation).+func askInChatWithoutForm(next mcp.MethodHandler) mcp.MethodHandler {+ return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {+ result, err := next(ctx, method, req)+ params, isInitialize := req.GetParams().(*mcp.InitializeParams)+ if initialized, ok := result.(*mcp.InitializeResult); ok && initialized != nil && isInitialize && !declaresFormElicitation(params) {+ initialized.Instructions += "\n\n" + askInChatInstructions}return result, err}@@ -260,7 +275,6 @@ func refuseSessionlessProtocol(next http.Handler) http.Handler {func (s *Server) registerTools() {s.registerSearchTool()s.registerCallTool()- s.registerSkillTool()s.registerQueryTool()s.registerSchemaTool()s.registerChangeTool()@@ -281,6 +295,26 @@ func requiresUserInteraction() mcp.Meta {return mcp.Meta{"anthropic/requiresUserInteraction": true}}+// serverInstructions route an agent to the right tool. A client may add them+// to the model's prompt for the whole session (MCP InitializeResult+// instructions). One server serves every workspace, and an admin can change a+// workspace's MCP access policy at any time, so they name no workspace and+// assume no mode.+const serverInstructions = `Bytebase governs access to databases and changes to them. Every call is also limited by the workspace's MCP access policy.++Choose the tool by task:+- Find a database: call_api(operationId="DatabaseService/SearchDatabases") lists the databases you can view.+- Read data: query_database. Before you write SQL for a database, read its schema with get_schema.+- Inspect a schema: get_schema.+- Change a database: propose_database_change, the easiest way into the governed workflow. It creates the plan and the issue and runs the plan checks; approval and rollout follow the project's policy. ` + singleDatabaseLimit + `+- Anything else: a tool whose description covers the task; failing that, search_api to find the operation and its request schema, then call_api.++When the workspace's MCP access policy is Read-write, query_database can also run DML and DDL, as far as the engine and the account's permissions allow; call_api refuses them. They take effect at once, without an issue or approval. Use propose_database_change for any change that should be reviewed, or when a write fails on a read-only data source.++When Bytebase refuses a call, the error states the reason and may name a next step, such as a tool to use.`++const askInChatInstructions = `This client cannot show Bytebase's confirmation form, so under Read-write query_database runs any statement that may write without asking. Before you run one, show the user the exact statement, say it runs at once with no issue or approval, and ask them to confirm.`+// authMiddleware validates OAuth2 bearer tokens for MCP requests.//// On 401, it emits an RFC 9728 / MCP-authorization-spec compliantdiff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.goindex 8ef0351f80..be0db12709 100644--- a/backend/api/mcp/server_test.go+++ b/backend/api/mcp/server_test.go@@ -5,13 +5,16 @@ import ("io""net/http""net/http/httptest"+ "regexp""strings""testing""time"+ "unicode/utf8""connectrpc.com/connect""github.com/golang-jwt/jwt/v5""github.com/labstack/echo/v5"+ "github.com/modelcontextprotocol/go-sdk/mcp""github.com/pkg/errors""github.com/stretchr/testify/require"@@ -596,14 +599,42 @@ func tokenForWorkspace(t *testing.T, secret, workspaceID string) string {return tokenStr}-func TestInitializeNamesTheSignedInAccount(t *testing.T) {+func listToolsOverRoute(t *testing.T) []*mcp.Tool {+ t.Helper()endpoint, _, _ := newProbeServer(t)- token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)-+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)session := connectLegacy(t, endpoint, token, nil)- require.Equal(t, `This session acts as the Bytebase account [email protected]: every tool call runs with its permissions, `+- `and "you" in tool results means it. The user may have other accounts with other emails, such as the client's own sign-in.`,- session.InitializeResult().Instructions)+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ listed, err := session.ListTools(ctx, nil)+ require.NoError(t, err)+ return listed.Tools+}++func TestInitializeServesInstructions(t *testing.T) {+ const account = `This session acts as the Bytebase account [email protected]: every tool call runs with its permissions, ` ++ `and "you" in tool results means it. The user may have other accounts with other emails, such as the client's own sign-in.`+ tools := listToolsOverRoute(t)+ for _, row := range []struct {+ name string+ options *mcp.ClientOptions+ instructions string+ }{+ {name: "a client without the form", instructions: account + "\n\n" + serverInstructions + "\n\n" + askInChatInstructions},+ {name: "a client with the form", options: &mcp.ClientOptions{ElicitationHandler: (&asker{}).handle}, instructions: account + "\n\n" + serverInstructions},+ } {+ t.Run(row.name, func(t *testing.T) {+ endpoint, _, _ := newProbeServer(t)+ session := connectLegacy(t, endpoint, mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour), row.options)+ require.Equal(t, row.instructions, session.InitializeResult().Instructions)+ })+ }+ for _, name := range []string{"query_database", "get_schema", "propose_database_change", "search_api", "call_api"} {+ require.Contains(t, serverInstructions, name)+ }+ for _, tool := range tools {+ require.NotEqual(t, "get_skill", tool.Name)+ }}// A second initialize on an open session is refused by the SDK with no result,@@ -634,3 +665,53 @@ func TestDuplicateInitializeIsRefusedAndTheServerKeepsServing(t *testing.T) {_, err = session.ListTools(ctx, nil)require.NoError(t, err, "the session must keep serving after the refused initialize")}++func TestServerInstructionsFitClientLimit(t *testing.T) {+ // No deliverable address is longer than 254 characters: RFC 5321+ // §4.5.3.1.3 caps a path at 256 octets, angle brackets included.+ email := strings.Repeat("a", 242) + "@example.com"+ endpoint, _, _ := newProbeServer(t)+ session := connectLegacy(t, endpoint, mintMCPToken(t, email, "client-A", "ws-test", "mcp:read-write", time.Hour), nil)+ instructions := session.InitializeResult().Instructions+ require.Contains(t, instructions, email)++ // Claude Code cuts server instructions at 4,096 characters, and before+ // v2.1.296 at 2,048 (code.claude.com/docs/en/mcp). Holding the older limit+ // keeps the confirmation sentence near the end on those versions too.+ require.LessOrEqual(t, utf8.RuneCountInString(instructions), 2048)+ require.Contains(t, instructions, "ask them to confirm")+}++func TestToolGuidanceNamesOnlyServedToolsAndOperations(t *testing.T) {+ tools := listToolsOverRoute(t)+ idx, err := NewOpenAPIIndex()+ require.NoError(t, err)++ registered := make(map[string]bool, len(tools))+ guidance := map[string]string{"server instructions": serverInstructions, "ask-in-chat instructions": askInChatInstructions}+ for _, tool := range tools {+ registered[tool.Name] = true+ guidance[tool.Name+" description"] = tool.Description+ }+ // Quoted strings are example values, such as a database named "employee_db".+ quoted := regexp.MustCompile(`"[^"]*"`)+ snakeCase := regexp.MustCompile(`\b[a-z]+(?:_[a-z]+)+\b`)+ // Any ID with a letter is checked, so a malformed one fails rather than+ // going unmatched; the operationId="..." placeholder has none.+ operationID := regexp.MustCompile(`operationId="([^"]*[A-Za-z][^"]*)"`)+ // The check sees only that spelling, so the instructions must write the+ // operation they route to as a call.+ require.NotEmpty(t, operationID.FindString(serverInstructions), "server instructions name no operationId=\"...\" call to check")+ for source, text := range guidance {+ for _, name := range snakeCase.FindAllString(quoted.ReplaceAllString(text, ""), -1) {+ require.True(t, registered[name], "%s names %q, which is not a registered tool", source, name)+ }+ for _, match := range operationID.FindAllStringSubmatch(text, -1) {+ endpoint, ok := idx.GetEndpoint(match[1])+ require.True(t, ok, "%s names operation %q, which call_api cannot resolve", source, match[1])+ class, err := auth.MCPMethodClassOfProcedure(endpoint.Path)+ require.NoError(t, err)+ require.False(t, auth.MCPClassIsRefused(class), "%s names operation %q, which is %v: no MCP session can call it", source, match[1], class)+ }+ }+}diff --git a/backend/api/mcp/skills/database-change.md b/backend/api/mcp/skills/database-change.mddeleted file mode 100644index 1c958c673e..0000000000--- a/backend/api/mcp/skills/database-change.md+++ /dev/null@@ -1,146 +0,0 @@-----name: database-change-description: Use when making schema changes (DDL), data migrations, ALTER TABLE, CREATE TABLE, or deploying SQL changes through review workflow------# Database Change--> **STOP: For single-database changes, call `propose_database_change(database="...", sql="...", title="...")` directly.** It handles everything (sheet, plan, plan checks, issue) in one call with plain SQL — no base64, no manual steps. Only use the manual workflow below for **batch changes across multiple databases**.--## Overview--Manual workflow for batch database changes (DDL/DML) across multiple databases through Bytebase's review workflow.--## Prerequisites--- Have `bb.plans.create`, `bb.issues.create`, `bb.rollouts.create` permissions-- Know the target database(s)--## Workflow--### Step 1: Create sheet(s) with SQL--SQL content must be **base64 encoded**.--```-search_api(operationId="SheetService/CreateSheet")-```-```-call_api(operationId="SheetService/CreateSheet", body={- "parent": "projects/{project-id}",- "sheet": {- "content": "Q1JFQVRFIFRBQkxFIHVzZXJzIChpZCBJTlQgUFJJTUFSWSBLRVkpOw=="- }-})-```--Note: `Q1JFQVRFIFRBQkxFIHVzZXJzIChpZCBJTlQgUFJJTUFSWSBLRVkpOw==` decodes to `CREATE TABLE users (id INT PRIMARY KEY);`--### Step 2: Create a plan--Plan contains `specs` directly (not wrapped in "steps").--**Single database:**-```-search_api(operationId="PlanService/CreatePlan")-```-```-call_api(operationId="PlanService/CreatePlan", body={- "parent": "projects/{project-id}",- "plan": {- "title": "Add users table",- "specs": [{- "id": "spec-1",- "changeDatabaseConfig": {- "targets": ["projects/{project-id}/instances/{instance-id}/databases/{database-name}"],- "sheet": "projects/{project-id}/sheets/{sheet-id}"- }- }]- }-})-```--**Batch change (multiple databases):**-```-call_api(operationId="PlanService/CreatePlan", body={- "parent": "projects/{project-id}",- "plan": {- "title": "Add users table to all databases",- "specs": [- {- "id": "spec-dev",- "changeDatabaseConfig": {- "targets": ["instances/dev-pg/databases/mydb"],- "sheet": "projects/{project-id}/sheets/{sheet-id}"- }- },- {- "id": "spec-prod",- "changeDatabaseConfig": {- "targets": ["instances/prod-pg/databases/mydb"],- "sheet": "projects/{project-id}/sheets/{sheet-id}"- }- }- ]- }-})-```--**Key concepts:**-- `specs` is a flat array directly on the plan (no "steps" wrapper)-- Each `spec` has a unique `id` (any string, used for identification)-- `targets` is an **array** (even for single database)-- Preserve the exact canonical database name returned by SearchDatabases or ListDatabases. A project instance- uses `projects/{project-id}/instances/{instance-id}/databases/{database-name}`;- do not shorten it to `instances/{instance-id}/databases/{database-name}`.-- Specs are executed based on rollout policy (can be sequential or parallel)--**Using database groups:**-```-"targets": ["projects/{project-id}/databaseGroups/{group-name}"]-```--### Step 3: Create an issue--```-search_api(operationId="IssueService/CreateIssue")-```-```-call_api(operationId="IssueService/CreateIssue", body={- "parent": "projects/{project-id}",- "issue": {- "title": "Add users table",- "type": "DATABASE_CHANGE",- "plan": "projects/{project-id}/plans/{plan-id}"- }-})-```--### Step 4: Create a rollout--```-search_api(operationId="RolloutService/CreateRollout")-```-```-call_api(operationId="RolloutService/CreateRollout", body={- "parent": "projects/{project-id}",- "rollout": {- "plan": "projects/{project-id}/plans/{plan-id}"- }-})-```--## Change Types--The backend auto-detects whether a change is imperative (DDL/DML) or SDL (declarative schema) from the sheet content. No `type` field is needed in the plan spec.--## Common Errors--| Error | Cause | Fix |-|-------|-------|-----|-| database not found | Wrong database reference | List databases and preserve its exact canonical `name` |-| sheet not found | Sheet doesn't exist | Create sheet first (Step 1) |-| missing engine | Sheet without engine field | Add `engine` field to sheet |-| plan not found | Plan doesn't exist | Create plan before issue |-| invalid base64 | SQL not encoded | Base64 encode the SQL content |-| targets must be array | Using string instead of array | Wrap target in array: `["..."]` |diff --git a/backend/api/mcp/skills/query.md b/backend/api/mcp/skills/query.mddeleted file mode 100644index ffa4aadbaa..0000000000--- a/backend/api/mcp/skills/query.md+++ /dev/null@@ -1,77 +0,0 @@-----name: query-description: Use when running SQL queries or fetching data from databases------# Execute SQL--## Overview--Run SQL queries against databases managed by Bytebase.--**Before writing SQL, call `get_schema(database=...)` to see the current shape.**--## Prerequisites--- Know the database's exact canonical resource name. Preserve the `name`- returned by SearchDatabases or ListDatabases; do not shorten a project instance- to `instances/{id}`.-- Have `bb.sql.query` permission--## Workflow--1. **Get the schema**:- ```- search_api(operationId="SQLService/Query")- ```--2. **Find the database** (if needed):- ```- search_api(operationId="DatabaseService/SearchDatabases")- ```- ```- call_api(operationId="DatabaseService/SearchDatabases", body={- "filter": "name.contains(\"db_name\")"- })- ```-- SearchDatabases returns databases from every active project where you have- `bb.databases.get`.-- Filter examples:- - `name.contains("employee")` - database name contains "employee"- - `project == "projects/{project-id}"` - databases in a project- - `instance == "instances/{instance-id}"` - databases in a workspace instance- - `instance == "projects/{project-id}/instances/{instance-id}"` - databases in a project instance- - `engine == "MYSQL"` - MySQL databases only- - `environment == "environments/prod" && name.contains("user")` - combine filters-- **Extract `dataSourceId`** from `instanceResource.dataSources` in the response. Prefer `type: "READ_ONLY"` over `type: "ADMIN"` when available.--3. **Execute SQL**:- ```- call_api(operationId="SQLService/Query", body={- "name": "projects/{project-id}/instances/{instance-id}/databases/{database-name}",- "dataSourceId": "{data-source-id}",- "statement": "SELECT * FROM users LIMIT 10"- })- ```-- `dataSourceId` is **required**.--## Notes--- Run a statement that may write, such as INSERT, UPDATE, DELETE or DDL, with the `query_database` tool. `call_api` refuses it.-- Query results may contain masked values due to data masking policies. Do not remove or modify masked values.- - Full mask: `******`- - Partial mask: `**rn**` (only "rn" visible)-- **Displaying partial masks:** Use backticks or code blocks when presenting results. Without escaping, markdown interprets `**text**` as bold formatting.--## Common Errors--| Error | Cause | Fix |-|-------|-------|-----|-| data source id is required | Missing dataSourceId field | Get dataSourceId from instanceResource.dataSources in database listing |-| database not found | Wrong instance/database name | List databases first and use its exact canonical `name` |-| permission denied | Missing bb.sql.query | Check user permissions |-| syntax error | Invalid SQL | Check SQL syntax for the database engine |diff --git a/backend/api/mcp/tool_access_request_test.go b/backend/api/mcp/tool_access_request_test.goindex ea45ca9271..6dab300872 100644--- a/backend/api/mcp/tool_access_request_test.go+++ b/backend/api/mcp/tool_access_request_test.go@@ -355,7 +355,7 @@ func TestOnlyTheGrantingToolsRequireUserInteraction(t *testing.T) {}slices.Sort(names)require.Equal(t, []string{- "call_api", "decide_issue", "get_schema", "get_skill", "grant_masking_exemption", "propose_database_change",+ "call_api", "decide_issue", "get_schema", "grant_masking_exemption", "propose_database_change","query_database", "reauthorize", "request_access_grant", "revoke_masking_exemption", "search_api", "set_just_in_time_access",}, names)require.ElementsMatch(t, []string{"request_access_grant", "grant_masking_exemption"}, flagged)diff --git a/backend/api/mcp/tool_change.go b/backend/api/mcp/tool_change.goindex 1f220e0075..7960d31a67 100644--- a/backend/api/mcp/tool_change.go+++ b/backend/api/mcp/tool_change.go@@ -121,6 +121,11 @@ func (e *changeError) Error() string {return fmt.Sprintf("%s: %s", e.Code, e.Message)}+// singleDatabaseLimit is shared with the server instructions, so the two+// cannot state different limits.+const singleDatabaseLimit = "It changes one database per call. For several databases in one plan, " ++ "ask the user to use the Bytebase console or GitOps."+// proposeChangeDescription is the description for the propose_database_change tool.const proposeChangeDescription = `Run DDL/DML changes (ALTER TABLE, CREATE TABLE, INSERT, UPDATE, migrations) against a Bytebase database.@@ -144,7 +149,7 @@ propose_database_change(database="app", sql="ALTER TABLE users ADD COLUMN statuspropose_database_change(database="app", sql="UPDATE orders SET status='shipped' WHERE id=42", title="Ship order 42", createRollout=true)**Notes:**-- v1 supports single database targets only. For batch changes across multiple databases, use get_skill("database-change").+- ` + singleDatabaseLimit + `- Plan checks run automatically; results included in response when available.- Requires bb.sheets.create, bb.plans.create, bb.issues.create permissions.- If createRollout=true but policy gates aren't satisfied, returns success with rolloutCreated=false and a reason.diff --git a/backend/api/mcp/tool_resolve.go b/backend/api/mcp/tool_resolve.goindex 3204f56a47..e4b3b442cd 100644--- a/backend/api/mcp/tool_resolve.go+++ b/backend/api/mcp/tool_resolve.go@@ -344,7 +344,12 @@ func acceptedDatabaseLabel(response mcp.InputResponse) (string, bool) {}func clientSupportsElicitation(session *mcp.ServerSession) bool {- params := session.InitializeParams()+ return declaresFormElicitation(session.InitializeParams())+}++// declaresFormElicitation reports whether params declare the form elicitation+// a confirmation needs.+func declaresFormElicitation(params *mcp.InitializeParams) bool {if params == nil || params.Capabilities == nil || params.Capabilities.Elicitation == nil {return false}diff --git a/backend/api/mcp/tool_skill.go b/backend/api/mcp/tool_skill.godeleted file mode 100644index ccd58a34d8..0000000000--- a/backend/api/mcp/tool_skill.go+++ /dev/null@@ -1,123 +0,0 @@-package mcp--import (- "context"- "embed"- "fmt"- "path/filepath"- "strings"-- "github.com/modelcontextprotocol/go-sdk/mcp"- "gopkg.in/yaml.v3"-)--//go:embed skills/*.md-var skillFiles embed.FS--// SkillInput is the input for the get_skill tool.-type SkillInput struct {- // Skill is the name of the skill to retrieve.- // Leave empty to list all available skills.- Skill string `json:"skill,omitempty"`-}--// skillMeta holds parsed skill metadata from frontmatter.-type skillMeta struct {- Name string `yaml:"name"`- Description string `yaml:"description"`-}--// getSkillDescription is the description for the get_skill tool.-const getSkillDescription = `Get step-by-step guides for Bytebase tasks.--**Tip:** Use query_database for SQL queries and propose_database_change for single-database DDL/DML — they handle resolution automatically.--**Workflow:** get_skill("task") → search_api(operationId) → call_api(...)--Skills: query, database-change`--func (s *Server) registerSkillTool() {- mcp.AddTool(s.mcpServer, &mcp.Tool{- Name: "get_skill",- Description: getSkillDescription,- }, s.handleGetSkill)-}--func (s *Server) handleGetSkill(_ context.Context, _ *mcp.CallToolRequest, input SkillInput) (*mcp.CallToolResult, any, error) {- if input.Skill == "" {- // List all skills- text := s.formatSkillList()- return &mcp.CallToolResult{- Content: []mcp.Content{&mcp.TextContent{Text: text}},- }, nil, nil- }-- // Get specific skill- text := s.getSkillContent(input.Skill)- return &mcp.CallToolResult{- Content: []mcp.Content{&mcp.TextContent{Text: text}},- }, nil, nil-}--func (*Server) formatSkillList() string {- var sb strings.Builder- sb.WriteString("## Available Skills\n\n")- sb.WriteString("Use `get_skill(skill=\"name\")` to get the full guide.\n\n")- sb.WriteString("| Skill | Description |\n")- sb.WriteString("|-------|-------------|\n")-- entries, _ := skillFiles.ReadDir("skills")- for _, entry := range entries {- if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".md") {- meta := parseSkillMeta(entry.Name())- if meta != nil {- fmt.Fprintf(&sb, "| %s | %s |\n", meta.Name, meta.Description)- }- }- }-- return sb.String()-}--func parseSkillMeta(filename string) *skillMeta {- content, err := skillFiles.ReadFile(filepath.Join("skills", filename))- if err != nil {- return nil- }-- // Parse YAML frontmatter- str := string(content)- if !strings.HasPrefix(str, "---") {- return nil- }-- end := strings.Index(str[3:], "---")- if end == -1 {- return nil- }-- var meta skillMeta- if err := yaml.Unmarshal([]byte(str[3:3+end]), &meta); err != nil {- return nil- }-- return &meta-}--func (*Server) getSkillContent(skillName string) string {- filename := skillName + ".md"- content, err := skillFiles.ReadFile(filepath.Join("skills", filename))- if err != nil {- return fmt.Sprintf("Skill %q not found. Use get_skill() to list available skills.", skillName)- }-- // Strip frontmatter for cleaner output- str := string(content)- if strings.HasPrefix(str, "---") {- if end := strings.Index(str[3:], "---"); end != -1 {- str = strings.TrimSpace(str[3+end+3:])- }- }-- return str-}diff --git a/backend/api/mcp/tool_skill_test.go b/backend/api/mcp/tool_skill_test.godeleted file mode 100644index 7522e6034a..0000000000--- a/backend/api/mcp/tool_skill_test.go+++ /dev/null@@ -1,134 +0,0 @@-package mcp--import (- "context"- "regexp"- "testing"-- mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"- "github.com/stretchr/testify/require"-- "github.com/bytebase/bytebase/backend/api/auth"- "github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/component/config"-)--func TestGetSkillListSkills(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)- require.NoError(t, err)-- // Test listing all skills (no parameters)- result, _, err := s.handleGetSkill(context.Background(), nil, SkillInput{})- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- require.Contains(t, text, "Available Skills")- require.Contains(t, text, "query")- require.Contains(t, text, "database-change")-}--func TestGetSkillSpecificSkill(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)- require.NoError(t, err)-- // Test getting query skill- result, _, err := s.handleGetSkill(context.Background(), nil, SkillInput{- Skill: "query",- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- require.Contains(t, text, "Execute SQL")- require.Contains(t, text, "SQLService/Query")- require.Contains(t, text, "Workflow")-}--func TestGetSkillNotFound(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)- require.NoError(t, err)-- // Test getting non-existent skill- result, _, err := s.handleGetSkill(context.Background(), nil, SkillInput{- Skill: "non-existent",- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- require.Contains(t, text, "not found")- require.Contains(t, text, "get_skill()")-}--func TestGetSkillAllSkillsLoadable(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)- require.NoError(t, err)-- skills := []string{"query", "database-change"}- for _, skill := range skills {- t.Run(skill, func(t *testing.T) {- result, _, err := s.handleGetSkill(context.Background(), nil, SkillInput{- Skill: skill,- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- require.NotContains(t, text, "skill \""+skill+"\" not found", "skill %s should be loadable", skill)- require.NotEmpty(t, text)- })- }-}--// TestSkillsOnlyInstructServableCalls is the rule that keeps a shipped skill-// honest: every operation a skill tells the agent to call must be one the MCP-// ceiling gate serves. It states the rule rather than fixing an instance of it,-// because the failure mode is silent — a classification change lands in a proto-// file, the skill keeps shipping, and the agent follows a playbook whose every-// step comes back 403.-//-// That is exactly what happened to the grant-permission skill: 1b-1 classified-// the five IAM operations it drove as EXCLUDED, 1b-2 turned EXCLUDED into a-// denial, and nothing connected the two. The skill is gone; this is what stops-// the next one going the same way.-//-// It resolves through the same index call_api uses, so an operation ID that no-// longer resolves fails here too.-func TestSkillsOnlyInstructServableCalls(t *testing.T) {- idx, err := NewOpenAPIIndex()- require.NoError(t, err)-- entries, err := skillFiles.ReadDir("skills")- require.NoError(t, err)- require.NotEmpty(t, entries, "the embedded skills directory must not be empty")-- operationID := regexp.MustCompile(`operationId="([^"]+)"`)- for _, entry := range entries {- t.Run(entry.Name(), func(t *testing.T) {- content, err := skillFiles.ReadFile("skills/" + entry.Name())- require.NoError(t, err)-- matches := operationID.FindAllStringSubmatch(string(content), -1)- require.NotEmpty(t, matches, "a skill that instructs no call is not a skill")- for _, match := range matches {- operation := match[1]- endpoint, ok := idx.GetEndpoint(operation)- require.True(t, ok, "%s instructs operation %q, which call_api cannot resolve", entry.Name(), operation)- class, err := auth.MCPMethodClassOfProcedure(endpoint.Path)- require.NoError(t, err, "%s instructs %q, whose classification cannot be read", entry.Name(), operation)- require.False(t, auth.MCPClassIsRefused(class),- "%s instructs %q, which is %v — no MCP ceiling serves it, so the skill cannot be followed",- entry.Name(), operation, class)- }- })- }-}