From cc7d8024119bb3da2df54d66ddb68d8466e0185c Mon Sep 17 00:00:00 2001 From: Willie Date: Tue, 6 Oct 2026 14:18:16 +0800 Subject: [PATCH] feat(mcp): serve skills over MCP with the SEP-2640 Skills extension Agents on a disposable VM, in a hosted assistant or behind an MCP gateway can reach an MCP endpoint but not the folder skills sync to, so they got tools and none of the user's skills (#428). `skillshare mcp serve` is a read-only server for the skills skillshare already manages. It declares io.modelcontextprotocol/skills and implements skills/list, skills/get and resources/read: one entry per skill, its URI from the source path, the full frontmatter, and every file with a sha256 digest and size. --target applies that target's selection, and the source is reread at most every 5 seconds so install, update, enable and disable show up without a restart; unchanged files keep their digest. stdio is the default; --http serves Streamable HTTP and needs SKILLSHARE_MCP_TOKEN off loopback. Skills the extension cannot carry are skipped with a warning instead of being published incomplete: a name that breaks the Agent Skills rules or differs from its directory, more than 512 files or 16 MiB, or a nested skill that is not served. --check lists them without serving. The naming rules moved to internal/skillpkg so sync and the server share them. Few clients support the extension yet, so the server also offers list_skills and read_skill tools. A client that declares the extension does not see them, so it never gets each skill twice. sync.SelectTargetSkills is the one place that turns discovered skills into a target's selection (enabled, include/exclude, frontmatter targets). Refs: #428 --- ai_docs/tests/mcp_serve_runbook.md | 178 +++++++++++++++++++ cmd/skillshare/completion_bash.go | 4 +- cmd/skillshare/completion_fish.go | 4 +- cmd/skillshare/completion_nushell.go | 4 +- cmd/skillshare/completion_powershell.go | 3 +- cmd/skillshare/completion_zsh.go | 4 +- cmd/skillshare/mcp.go | 4 + cmd/skillshare/mcp_serve.go | 160 +++++++++++++++++ go.mod | 12 +- go.sum | 28 ++- internal/skillpkg/skillpkg.go | 118 +++++++++++++ internal/skillserve/catalog.go | 220 ++++++++++++++++++++++++ internal/skillserve/catalog_test.go | 189 ++++++++++++++++++++ internal/skillserve/server.go | 220 ++++++++++++++++++++++++ internal/skillserve/server_test.go | 183 ++++++++++++++++++++ internal/skillserve/tools.go | 117 +++++++++++++ internal/sync/filter.go | 12 ++ internal/sync/filter_target_test.go | 15 ++ internal/sync/target_naming.go | 30 +--- internal/utils/frontmatter.go | 13 ++ skills/skillshare/SKILL.md | 4 +- skills/skillshare/references/mcp.md | 13 ++ tests/integration/completion_test.go | 10 +- tests/integration/mcp_serve_test.go | 105 +++++++++++ website/docs/reference/commands/mcp.md | 95 +++++++++- 25 files changed, 1698 insertions(+), 47 deletions(-) create mode 100644 ai_docs/tests/mcp_serve_runbook.md create mode 100644 cmd/skillshare/mcp_serve.go create mode 100644 internal/skillpkg/skillpkg.go create mode 100644 internal/skillserve/catalog.go create mode 100644 internal/skillserve/catalog_test.go create mode 100644 internal/skillserve/server.go create mode 100644 internal/skillserve/server_test.go create mode 100644 internal/skillserve/tools.go create mode 100644 tests/integration/mcp_serve_test.go diff --git a/ai_docs/tests/mcp_serve_runbook.md b/ai_docs/tests/mcp_serve_runbook.md new file mode 100644 index 000000000..927cfaa1c --- /dev/null +++ b/ai_docs/tests/mcp_serve_runbook.md @@ -0,0 +1,178 @@ +# CLI E2E Runbook: `skillshare mcp serve` + +Validates the read-only SEP-2640 skills server over stdio and Streamable HTTP. + +**Origin**: issue #428 — Agents that only reach an MCP endpoint need the skills Skillshare manages. + +## Scope + +- `server/discover` declares `resources` and the `io.modelcontextprotocol/skills` extension +- `skills/list` returns one entry per valid, enabled skill with frontmatter and a complete sha256 manifest +- A skill whose `name` differs from its directory is skipped with a stderr warning; a disabled skill is not served +- `--check` lists skipped skills and the served count without serving +- `--target` applies that target's `exclude` filter +- `resources/read` returns a listed file and rejects a URI that escapes the skill +- Over HTTP: bearer token required, a newly added skill appears without a restart +- A non-loopback `--http` address without `SKILLSHARE_MCP_TOKEN` is refused + +## Environment + +Run inside the devcontainer with a fresh ssenv HOME: + +```bash +ssenv create mcp-serve-e2e --init +ssenv enter mcp-serve-e2e -- mdproof --report json /workspace/ai_docs/tests/mcp_serve_runbook.md +``` + +Every step works from `$HOME` and points `SKILLSHARE_CONFIG` at `$HOME/mcp-serve/config.yaml`. +The server drops requests still in flight when stdin closes, so stdio steps keep stdin open +with `sleep 1`. Step 6 listens on port 47941; pick another free port if it is taken. + +## Steps + +### Step 1: Discover and list over stdio + +```bash +set -eu +cd "$HOME" +CASE="$HOME/mcp-serve" +rm -rf "$CASE" +mkdir -p "$CASE/skills" +export SKILLSHARE_CONFIG="$CASE/config.yaml" +cat > "$SKILLSHARE_CONFIG" < "$CASE/skills/$n/SKILL.md" +done +mkdir -p "$CASE/skills/pdf/references" "$CASE/skills/renamed" +echo forms > "$CASE/skills/pdf/references/FORMS.md" +printf -- '---\nname: original\ndescription: Use when testing\n---\n# Renamed\n' > "$CASE/skills/renamed/SKILL.md" +echo off > "$CASE/skills/.skillignore" +M='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"e2e","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}' +{ printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"server/discover\",\"params\":{$M}}" "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"skills/list\",\"params\":{$M}}"; sleep 1; } \ + | ss mcp serve -g 2>"$CASE/stderr" | jq -sc 'map({(.id|tostring): .result}) | add' +``` + +Expected: +- exit_code: 0 +- jq: .["1"].capabilities.extensions | has("io.modelcontextprotocol/skills") +- jq: .["1"].capabilities.resources == {} +- jq: [.["2"].skills[].uri] == ["skill://notes/SKILL.md", "skill://pdf/SKILL.md"] +- jq: .["2"].resultType == "complete" +- jq: (.["2"].skills[] | select(.uri == "skill://pdf/SKILL.md") | [.resources[].uri] | sort) == ["skill://pdf/SKILL.md", "skill://pdf/references/FORMS.md"] +- jq: [.["2"].skills[].resources[].digest | test("^sha256:[0-9a-f]{64}$")] | all + +### Step 2: The renamed skill is reported on stderr + +```bash +cat "$HOME/mcp-serve/stderr" +``` + +Expected: +- exit_code: 0 +- skipped renamed: SKILL.md name "original" does not match directory name "renamed" + +### Step 3: `--check` lists the skipped skill without serving + +```bash +cd "$HOME" +export SKILLSHARE_CONFIG="$HOME/mcp-serve/config.yaml" +NO_COLOR=1 ss mcp serve --check -g < /dev/null +``` + +Expected: +- exit_code: 0 +- SKILL.md name "original" does not match directory name "renamed" +- 2 skills served, 1 skipped + +### Step 4: `--target` applies the target's exclude filter + +```bash +set -eu +cd "$HOME" +export SKILLSHARE_CONFIG="$HOME/mcp-serve/config.yaml" +M='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"e2e","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}' +{ printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"skills/list\",\"params\":{$M}}"; sleep 1; } \ + | ss mcp serve -g --target claude 2>/dev/null | jq -c .result +``` + +Expected: +- exit_code: 0 +- jq: [.skills[].uri] == ["skill://pdf/SKILL.md"] + +### Step 5: Read a listed file; reject an escaping URI + +```bash +set -eu +cd "$HOME" +export SKILLSHARE_CONFIG="$HOME/mcp-serve/config.yaml" +M='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"e2e","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}' +{ printf '%s\n' \ + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"resources/read\",\"params\":{$M,\"uri\":\"skill://pdf/references/FORMS.md\"}}" \ + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"resources/read\",\"params\":{$M,\"uri\":\"skill://pdf/%2e%2e/notes/SKILL.md\"}}"; sleep 1; } \ + | ss mcp serve -g 2>/dev/null | jq -sc 'map({(.id|tostring): .}) | add' +``` + +Expected: +- exit_code: 0 +- jq: .["1"].result.contents[0].text == "forms\n" +- jq: .["2"].error.code == -32602 + +### Step 6: HTTP needs the token and picks up a new skill without a restart + +```bash +set -eu +cd "$HOME" +CASE="$HOME/mcp-serve" +export SKILLSHARE_CONFIG="$CASE/config.yaml" +export SKILLSHARE_MCP_TOKEN=e2e-token +ss mcp serve -g --http 127.0.0.1:47941 2>/dev/null & +PID=$! +trap 'kill $PID 2>/dev/null || true' EXIT +for _ in 1 2 3 4 5 6 7 8 9 10; do curl -s -o /dev/null http://127.0.0.1:47941/ && break; sleep 0.5; done +M='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"e2e","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}' +list() { + curl -s -X POST http://127.0.0.1:47941/ -H 'Content-Type: application/json' \ + -H 'Accept: application/json, text/event-stream' -H 'MCP-Protocol-Version: 2026-07-28' \ + -H 'Mcp-Method: skills/list' "$@" \ + -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"skills/list\",\"params\":{$M}}" +} +UNAUTH=$(list -o /dev/null -w '%{http_code}') +BEFORE=$(list -H "Authorization: Bearer $SKILLSHARE_MCP_TOKEN" | sed -n 's/^data: //p' | jq '.result.skills | length') +mkdir -p "$CASE/skills/late" +printf -- '---\nname: late\ndescription: Use when testing late\n---\n# late\n' > "$CASE/skills/late/SKILL.md" +sleep 6 +AFTER=$(list -H "Authorization: Bearer $SKILLSHARE_MCP_TOKEN" | sed -n 's/^data: //p' | jq '.result.skills | length') +jq -nc --arg u "$UNAUTH" --argjson b "$BEFORE" --argjson a "$AFTER" '{unauth: $u, before: $b, after: $a}' +``` + +Expected: +- exit_code: 0 +- jq: .unauth == "401" +- jq: .before == 2 +- jq: .after == 3 + +### Step 7: A network listener without a token is refused + +```bash +cd "$HOME" +export SKILLSHARE_CONFIG="$HOME/mcp-serve/config.yaml" +unset SKILLSHARE_MCP_TOKEN +ss mcp serve -g --http 0.0.0.0:47942 +``` + +Expected: +- exit_code: 1 +- SKILLSHARE_MCP_TOKEN + +## Pass Criteria + +- All steps marked PASS +- No `ss mcp serve` process remains after Step 6 diff --git a/cmd/skillshare/completion_bash.go b/cmd/skillshare/completion_bash.go index ad684ce57..8962acb07 100644 --- a/cmd/skillshare/completion_bash.go +++ b/cmd/skillshare/completion_bash.go @@ -38,7 +38,7 @@ _skillshare() { local unlink_flags="--help -h" local list_flags="--verbose -v --json -j --no-tui --type -t --status --sort -s --all --help -h" local sync_flags="--all --dry-run -n --force -f --json --quiet -q --help -h" - local mcp_flags="--tools-allow --tools-deny --pi-options --url --target --from --file --sync --replace --disabled --keep-files --revision --dry-run -n --json --no-tui --no-dns --live --timeout --help -h" + local mcp_flags="--tools-allow --tools-deny --pi-options --url --target --from --file --sync --replace --disabled --keep-files --revision --dry-run -n --json --no-tui --no-dns --live --timeout --http --check --help -h" local status_flags="--json --help -h" local hooks_flags="--file --from --sync --replace --keep-files --revision --dry-run -n --json --help -h" local diff_flags="--no-tui --patch --stat --json --help -h" @@ -256,7 +256,7 @@ _skillshare() { list) COMPREPLY=($(compgen -W "${list_flags} ${global_flags}" -- "${cur}")) ;; sync) COMPREPLY=($(compgen -W "${sync_flags} ${global_flags}" -- "${cur}")) ;; plugin) COMPREPLY=($(compgen -W "add discover import list inspect sync check update enable disable remove --target --from --plugin --name --source-ref --entry --revision --dry-run -n --json --no-tui --help -h ${global_flags}" -- "${cur}")) ;; - mcp) COMPREPLY=($(compgen -W "add check edit import list remove restore ${mcp_flags} ${global_flags}" -- "${cur}")) ;; + mcp) COMPREPLY=($(compgen -W "add check edit import list remove restore serve ${mcp_flags} ${global_flags}" -- "${cur}")) ;; status) COMPREPLY=($(compgen -W "${status_flags} ${global_flags}" -- "${cur}")) ;; hooks) COMPREPLY=($(compgen -W "add disable edit enable import list remove restore sync ${hooks_flags} ${global_flags}" -- "${cur}")) ;; diff) COMPREPLY=($(compgen -W "${diff_flags} ${global_flags}" -- "${cur}")) ;; diff --git a/cmd/skillshare/completion_fish.go b/cmd/skillshare/completion_fish.go index 5748c2618..196f75b2d 100644 --- a/cmd/skillshare/completion_fish.go +++ b/cmd/skillshare/completion_fish.go @@ -52,6 +52,8 @@ complete -c skillshare -n '__fish_skillshare_using_command mcp' -l pi-options -r complete -c skillshare -n '__fish_skillshare_using_command mcp' -l no-dns -d 'Skip host lookups' complete -c skillshare -n '__fish_skillshare_using_command mcp' -l live -d 'check: start or call each server' complete -c skillshare -n '__fish_skillshare_using_command mcp' -l timeout -r -d 'check --live: per-server timeout' +complete -c skillshare -n '__fish_skillshare_using_command mcp' -l http -r -d 'serve: Streamable HTTP listen address' +complete -c skillshare -n '__fish_skillshare_using_command mcp' -l check -d 'serve: list skipped skills without serving' complete -c skillshare -n '__fish_skillshare_using_command mcp' -l url -r -d 'MCP endpoint' complete -c skillshare -n '__fish_skillshare_using_command mcp' -l target -r -a 'claude codex cursor vscode opencode kilocode grok antigravity amp claude-desktop cline copilot factory gemini goose junie kiro lmstudio warp windsurf pi omp' -d 'Receiving client' complete -c skillshare -n '__fish_skillshare_using_command mcp' -l from -r -a 'claude codex cursor vscode opencode kilocode grok antigravity amp claude-desktop cline copilot factory gemini goose junie kiro lmstudio warp windsurf pi omp' -d 'Import client' @@ -65,7 +67,7 @@ complete -c skillshare -n '__fish_skillshare_using_command mcp' -l dry-run -s n complete -c skillshare -n '__fish_skillshare_using_command mcp' -l json -d 'JSON output' complete -c skillshare -n '__fish_skillshare_using_command mcp' -l no-tui -d 'Disable interactive menus' complete -c skillshare -n '__fish_skillshare_using_command mcp' -l help -s h -d 'Show help' -complete -c skillshare -n '__fish_skillshare_using_command mcp' -a 'add check edit import list remove restore' +complete -c skillshare -n '__fish_skillshare_using_command mcp' -a 'add check edit import list remove restore serve' complete -c skillshare -n __fish_skillshare_no_subcommand -a hooks -d 'Manage Agent hooks' complete -c skillshare -n '__fish_skillshare_using_command hooks' -a 'add disable edit enable import list remove restore sync' complete -c skillshare -n '__fish_skillshare_using_command hooks' -l file -r -F -d 'Entry or native file' diff --git a/cmd/skillshare/completion_nushell.go b/cmd/skillshare/completion_nushell.go index 624f03198..bb07a9257 100644 --- a/cmd/skillshare/completion_nushell.go +++ b/cmd/skillshare/completion_nushell.go @@ -50,7 +50,7 @@ def "nu-complete skillshare plugin" [] { } def "nu-complete skillshare mcp" [] { - [add check edit import list remove restore] + [add check edit import list remove restore serve] } def "nu-complete skillshare mcp-target" [] { @@ -89,6 +89,8 @@ export extern "skillshare mcp" [ --no-dns # Skip host lookups --live # check: start or call each server --timeout: string # check --live: per-server timeout, such as 10s + --http: string # serve: Streamable HTTP listen address + --check # serve: list skipped skills without serving --no-tui --project(-p) --global(-g) diff --git a/cmd/skillshare/completion_powershell.go b/cmd/skillshare/completion_powershell.go index 4f8d2c072..8deca7e78 100644 --- a/cmd/skillshare/completion_powershell.go +++ b/cmd/skillshare/completion_powershell.go @@ -54,6 +54,7 @@ $_skillshareCompleter = { @{ Name = 'list'; Desc = 'MCP list' } @{ Name = 'remove'; Desc = 'MCP remove' } @{ Name = 'restore'; Desc = 'MCP restore' } + @{ Name = 'serve'; Desc = 'MCP serve' } ) 'hooks' = @( @{ Name = 'add'; Desc = 'Hooks add' } @@ -207,7 +208,7 @@ $_skillshareCompleter = { 'enable' = '--dry-run', '-n', '--kind', '--help', '-h', '--project', '-p', '--global', '-g' 'disable' = '--dry-run', '-n', '--kind', '--help', '-h', '--project', '-p', '--global', '-g' 'analyze' = '--verbose', '-v', '--filter', '--no-tui', '--json', '--help', '-h', '--project', '-p', '--global', '-g' - 'mcp' = '--tools-allow', '--tools-deny', '--pi-options', '--target', '--from', '--url', '--file', '--sync', '--replace', '--disabled', '--keep-files', '--revision', '--dry-run', '-n', '--json', '--no-dns', '--live', '--timeout', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' + 'mcp' = '--tools-allow', '--tools-deny', '--pi-options', '--target', '--from', '--url', '--file', '--sync', '--replace', '--disabled', '--keep-files', '--revision', '--dry-run', '-n', '--json', '--no-dns', '--live', '--timeout', '--http', '--check', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' 'plugin' = '--target', '--from', '--plugin', '--name', '--source-ref', '--entry', '--revision', '--dry-run', '-n', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' 'extras memory' = '--from', '--version', '--search', '--update-mode', '--json', '--help', '-h', '--project', '-p', '--global', '-g' 'extras' = '--mode', '--target', '--source', '--file', '--as', '--flatten', '--no-flatten', '--add-target', '--remove-target', '--prune', '--from', '--dry-run', '--force', '-f', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g' diff --git a/cmd/skillshare/completion_zsh.go b/cmd/skillshare/completion_zsh.go index 429031abe..dd5bc1a7a 100644 --- a/cmd/skillshare/completion_zsh.go +++ b/cmd/skillshare/completion_zsh.go @@ -96,7 +96,7 @@ _skillshare() { ;; mcp) _arguments \ - '1:command:(add check edit import list remove restore)' \ + '1:command:(add check edit import list remove restore serve)' \ '--tools-allow[Only these tools, comma-separated, * matches any characters; empty clears]:tools:' \ '--tools-deny[Never these tools, comma-separated, * matches any characters; empty clears]:tools:' \ '--pi-options[Other Pi built-in per-server fields as JSON]:json:' \ @@ -115,6 +115,8 @@ _skillshare() { '--no-dns[Skip host lookups]' \ '--live[check: start or call each server]' \ '--timeout[check --live: per-server timeout]:duration:' \ + '--http[serve: Streamable HTTP listen address]:address:' \ + '--check[serve: list skipped skills without serving]' \ '--no-tui[Disable interactive menus]' \ $global_flags \ '--help[Show help]' \ diff --git a/cmd/skillshare/mcp.go b/cmd/skillshare/mcp.go index 20ba3ac09..19239b7a2 100644 --- a/cmd/skillshare/mcp.go +++ b/cmd/skillshare/mcp.go @@ -154,6 +154,9 @@ func cmdMCP(args []string) (resultErr error) { args = append([]string{"list"}, args...) } sub, args := args[0], args[1:] + if sub == "serve" { + return cmdMCPServe(args) + } service, rest, err := mcpContext(args) if err != nil { return err @@ -387,6 +390,7 @@ func printMCPHelp() { {"check [name...]", "Verify variables, commands, hosts and sync state (--no-dns);\n--live also starts or calls each server [--timeout 10s]"}, {"remove [name]", "Select and remove a source entry; optionally sync removal,\nor stop managing it and keep its Agent entries (--keep-files)"}, {"restore [id]", "Browse backups, preview and restore Agent entries"}, + {"serve", "Serve skills read-only over MCP (SEP-2640) on stdio, or\n--http [--target ]; global unless -p;\n--check lists skipped skills without serving"}, }}, helpGroup{title: "Options", rows: []helpRow{ {"--target ", "Receiving client; repeat for several, or none to keep the\nserver in Skillshare without writing it to any Agent"}, diff --git a/cmd/skillshare/mcp_serve.go b/cmd/skillshare/mcp_serve.go new file mode 100644 index 000000000..db673fd53 --- /dev/null +++ b/cmd/skillshare/mcp_serve.go @@ -0,0 +1,160 @@ +package main + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "skillshare/internal/config" + "skillshare/internal/skillserve" + "skillshare/internal/ui" +) + +const mcpServeUsage = "skillshare mcp serve [--target ] [--http | --check] [-g|-p]" + +// mcpServeTokenEnv holds the bearer token HTTP clients must send. +const mcpServeTokenEnv = "SKILLSHARE_MCP_TOKEN" + +// cmdMCPServe serves the managed skills over MCP (SEP-2640). It never writes: +// stdout carries the protocol, so diagnostics go to stderr. +func cmdMCPServe(args []string) error { + mode, rest, err := parseModeArgs(args, "--target", "--http") + if err != nil { + return err + } + var target, addr string + check := false + for i := 0; i < len(rest); i++ { + switch a := rest[i]; a { + case "--check": + check = true + case "--target", "--http": + if i+1 == len(rest) { + return fmt.Errorf("%s requires a value", a) + } + i++ + if a == "--target" { + target = rest[i] + } else { + addr = rest[i] + } + default: + return fmt.Errorf("unknown mcp serve argument %q; usage: %s", a, mcpServeUsage) + } + } + if check && addr != "" { + return fmt.Errorf("--check starts no server; drop --http") + } + + // A gateway chooses the working directory, so only -p selects project mode. + b := &skillserve.Builder{Target: target} + var targets map[string]config.TargetConfig + if mode == modeProject { + cwd, err := os.Getwd() + if err != nil { + return err + } + rt, err := loadProjectRuntime(cwd) + if err != nil { + return err + } + b.Source, b.Walk, targets = rt.sourcePath, rt.skillsWalk(), rt.targets + } else { + cfg, err := config.Load() + if err != nil { + return err + } + b.Source, b.Walk, targets = cfg.EffectiveSkillsSource(), cfg.SkillsWalk(), cfg.Targets + } + if target != "" { + tc, ok := targets[target] + if !ok { + return fmt.Errorf("unknown target %q", target) + } + sc := tc.SkillsConfig() + if !sc.IsEnabled() { + return fmt.Errorf("target %q has skills disabled", target) + } + b.Skills = &sc + } + if check { + return printMCPServeCheck(b) + } + + token := os.Getenv(mcpServeTokenEnv) + if addr != "" && token == "" && !isLoopbackAddr(addr) { + return fmt.Errorf("refusing to serve on %s without authentication: set %s, or bind a loopback address such as 127.0.0.1:8765", addr, mcpServeTokenEnv) + } + + srv, err := skillserve.NewServer(b, skillserve.Options{Version: version, Warn: os.Stderr, Refresh: 5 * time.Second}) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + if addr == "" { + return srv.Run(ctx, &mcp.StdioTransport{}) + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + httpSrv := &http.Server{Handler: skillserve.HTTPHandler(srv, token), ReadHeaderTimeout: 10 * time.Second} + go func() { + <-ctx.Done() + httpSrv.Close() + }() + fmt.Fprintf(os.Stderr, "Serving skills over MCP at http://%s/\n", ln.Addr()) + if err := httpSrv.Serve(ln); !errors.Is(err, http.ErrServerClosed) { + return err + } + return nil +} + +// printMCPServeCheck builds the catalog the server would serve and lists the +// skills it would skip, without starting a server. +func printMCPServeCheck(b *skillserve.Builder) error { + start := time.Now() + c, err := b.Build() + if err != nil { + return err + } + labels := make([]string, len(c.Skipped)) + for i, s := range c.Skipped { + labels[i] = s.Path + } + width := ui.RowWidth(labels...) + for _, s := range c.Skipped { + ui.Row(ui.MarkWarn, s.Path, s.Reason, width) + } + text, mark := plural(len(c.Skills), "skill")+" served", ui.MarkOK + if len(c.Skipped) > 0 { + text, mark = text+fmt.Sprintf(", %d skipped", len(c.Skipped)), ui.MarkWarn + } + ui.Done(mark, text, time.Since(start)) + return nil +} + +// isLoopbackAddr reports whether a listen address only accepts local +// connections. An empty host listens on every interface. +func isLoopbackAddr(addr string) bool { + host, _, err := net.SplitHostPort(addr) + if err != nil || host == "" { + return false + } + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} diff --git a/go.mod b/go.mod index 7c5fc5999..635b4f01e 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module skillshare go 1.25.5 require ( - github.com/yuin/goldmark v1.7.8 github.com/charmbracelet/bubbles v1.0.0 github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/glamour v0.10.0 @@ -12,12 +11,14 @@ require ( github.com/charmbracelet/x/ansi v0.11.6 github.com/gofrs/flock v0.12.1 github.com/mattn/go-runewidth v0.0.19 + github.com/modelcontextprotocol/go-sdk v1.8.0 github.com/muesli/termenv v0.16.0 github.com/pelletier/go-toml/v2 v2.2.4 github.com/pterm/pterm v0.12.82 github.com/sergi/go-diff v1.4.0 github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a - golang.org/x/sys v0.38.0 + github.com/yuin/goldmark v1.7.8 + golang.org/x/sys v0.41.0 golang.org/x/term v0.32.0 gopkg.in/yaml.v3 v3.0.1 ) @@ -43,6 +44,7 @@ require ( github.com/dlclark/regexp2 v1.11.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/google/jsonschema-go v0.4.3 // indirect github.com/gookit/color v1.5.4 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/lithammer/fuzzysearch v1.1.8 // indirect @@ -57,8 +59,14 @@ require ( github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.16.0 // indirect github.com/sahilm/fuzzy v0.1.1 // indirect + github.com/segmentio/asm v1.1.3 // indirect + github.com/segmentio/encoding v0.5.4 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect golang.org/x/net v0.33.0 // indirect + golang.org/x/oauth2 v0.35.0 // indirect + golang.org/x/sync v0.20.0 // indirect golang.org/x/text v0.26.0 // indirect + golang.org/x/time v0.15.0 // indirect ) diff --git a/go.sum b/go.sum index c2bc282bc..77b4af23b 100644 --- a/go.sum +++ b/go.sum @@ -88,8 +88,12 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0= -github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= -github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0= +github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ= github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= @@ -127,6 +131,8 @@ github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwX github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= +github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4= +github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= @@ -156,6 +162,10 @@ github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWb github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA= github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= +github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= +github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= @@ -170,6 +180,8 @@ github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a/go.mod h1:DFSS3NA github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= @@ -188,9 +200,13 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -204,8 +220,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -220,10 +236,14 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/skillpkg/skillpkg.go b/internal/skillpkg/skillpkg.go new file mode 100644 index 000000000..22a390d08 --- /dev/null +++ b/internal/skillpkg/skillpkg.go @@ -0,0 +1,118 @@ +// Package skillpkg reads one skill directory as an Agent Skills package: its +// full frontmatter and every regular file, within the SEP-2640 limits. It has +// no configuration dependencies, so sync can share its naming rules. +package skillpkg + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "skillshare/internal/sourcewalk" + "skillshare/internal/utils" +) + +// Per-skill limits from SEP-2640. +const ( + MaxFiles = 512 + MaxBytes = 16 << 20 +) + +// File is one regular file of a package. +type File struct { + Path string // absolute + Rel string // slash-separated, relative to the package directory + Size int64 + ModTime time.Time +} + +// Package is a valid skill directory. +type Package struct { + Dir string // resolved + Frontmatter map[string]any + Files []File +} + +// Load reads the skill in dir. The error says why the directory is not a +// valid package. .git directories are left out; links are neither listed nor read. +func Load(dir string) (*Package, error) { + dirName := filepath.Base(filepath.Clean(dir)) // a followed link's name, not its target's + dir = utils.ResolveSymlink(dir) + content, err := os.ReadFile(filepath.Join(dir, "SKILL.md")) + if err != nil { + return nil, err + } + fm, err := utils.ParseFrontmatterMap(content) + if err != nil { + return nil, fmt.Errorf("SKILL.md has %w", err) + } + name, _ := fm["name"].(string) + if reason := ValidateName(name, dirName); reason != "" { + return nil, fmt.Errorf("%s", reason) + } + if desc, _ := fm["description"].(string); strings.TrimSpace(desc) == "" { + return nil, fmt.Errorf("SKILL.md is missing a description") + } + + p := &Package{Dir: dir, Frontmatter: fm} + var total int64 + err = sourcewalk.Walk(dir, sourcewalk.Options{}, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() { + if info.Name() == ".git" { + return filepath.SkipDir + } + return nil + } + if !info.Mode().IsRegular() { + return nil + } + if len(p.Files) == MaxFiles { + return fmt.Errorf("has more than %d files", MaxFiles) + } + if total += info.Size(); total > MaxBytes { + return fmt.Errorf("is larger than 16 MiB") + } + rel, err := filepath.Rel(dir, path) + if err != nil { + return err + } + p.Files = append(p.Files, File{Path: path, Rel: filepath.ToSlash(rel), Size: info.Size(), ModTime: info.ModTime()}) + return nil + }) + if err != nil { + return nil, err + } + return p, nil +} + +// ValidateName returns why a SKILL.md name breaks the Agent Skills naming rules +// (including name == directory name), or "" when it follows them. +func ValidateName(name, dirName string) string { + if name == "" { + return "SKILL.md is missing a name" + } + if len(name) > 64 { + return fmt.Sprintf("SKILL.md name %q is longer than 64 characters", name) + } + if strings.HasPrefix(name, "-") || strings.HasSuffix(name, "-") { + return fmt.Sprintf("SKILL.md name %q cannot start or end with '-'", name) + } + if strings.Contains(name, "--") { + return fmt.Sprintf("SKILL.md name %q cannot contain consecutive hyphens", name) + } + for _, r := range name { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' { + continue + } + return fmt.Sprintf("SKILL.md name %q must use only lowercase letters, numbers, and hyphens", name) + } + if name != dirName { + return fmt.Sprintf("SKILL.md name %q does not match directory name %q", name, dirName) + } + return "" +} diff --git a/internal/skillserve/catalog.go b/internal/skillserve/catalog.go new file mode 100644 index 000000000..7b80c237d --- /dev/null +++ b/internal/skillserve/catalog.go @@ -0,0 +1,220 @@ +// Package skillserve publishes the skills source as an MCP Skills extension +// (SEP-2640) catalog: one entry per valid skill with its full frontmatter and a +// complete file manifest, and contained reads of the listed files. +package skillserve + +import ( + "errors" + "fmt" + "io" + "net/url" + "os" + "slices" + "strings" + "time" + + "skillshare/internal/config" + "skillshare/internal/skillpkg" + "skillshare/internal/sourcewalk" + ssync "skillshare/internal/sync" + "skillshare/internal/utils" +) + +// extensionID is the SEP-2640 capability key. +const extensionID = "io.modelcontextprotocol/skills" + +var errNotFound = errors.New("not found") + +// File is one manifest entry of a skill. +type File struct { + URI string `json:"uri"` + Digest string `json:"digest"` + Size int64 `json:"size"` +} + +// Skill is one skills/list entry. +type Skill struct { + URI string `json:"uri"` + Frontmatter map[string]any `json:"frontmatter"` + Resources []File `json:"resources"` +} + +// servedFile locates a manifest file: the resolved skill directory and the +// slash path inside it. +type servedFile struct{ dir, rel string } + +// Skip is a skill left out of the catalog, by source path. +type Skip struct { + Path, Reason string +} + +func (s Skip) String() string { return fmt.Sprintf("skipped %s: %s", s.Path, s.Reason) } + +// Catalog is one snapshot of the served skills, ordered by source path. +type Catalog struct { + Skills []*Skill + Skipped []Skip + bySkill map[string]*Skill + byFile map[string]servedFile +} + +// Builder builds catalogs from the skills source. It keeps the digests of the +// last build so unchanged files are not hashed again. +type Builder struct { + Source string + Walk sourcewalk.Options + // Target names the target whose Skills selection applies. With Skills nil, + // every enabled skill is served. + Target string + Skills *config.ResourceTargetConfig + + digests map[string]digest +} + +type digest struct { + size int64 + mtime time.Time + sum string +} + +// Build discovers the source and returns the skills to serve. Skills that are +// invalid, over the limits, or contain an unserved nested skill are skipped +// with a warning. +func (b *Builder) Build() (*Catalog, error) { + all, err := ssync.DiscoverSourceSkillsAll(b.Source, b.Walk) + if err != nil { + return nil, err + } + var selected []ssync.DiscoveredSkill + if b.Skills != nil { + if selected, err = ssync.SelectTargetSkills(all, b.Target, *b.Skills); err != nil { + return nil, err + } + } else { + selected = slices.DeleteFunc(slices.Clone(all), func(s ssync.DiscoveredSkill) bool { return s.Disabled }) + } + served := make(map[string]bool, len(selected)) + for _, s := range selected { + served[s.RelPath] = true + } + var unserved []string + for _, s := range all { + if !served[s.RelPath] { + unserved = append(unserved, s.RelPath) + } + } + slices.SortFunc(selected, func(x, y ssync.DiscoveredSkill) int { return strings.Compare(x.RelPath, y.RelPath) }) + + c := &Catalog{bySkill: map[string]*Skill{}, byFile: map[string]servedFile{}} + next := map[string]digest{} + for _, s := range selected { + skill, reason := b.load(s, unserved, c.byFile, next) + if reason != "" { + c.Skipped = append(c.Skipped, Skip{Path: s.RelPath, Reason: reason}) + continue + } + c.Skills = append(c.Skills, skill) + c.bySkill[skill.URI] = skill + } + b.digests = next + return c, nil +} + +// load builds one entry and registers its files in byFile, or returns why the +// skill is skipped. +func (b *Builder) load(s ssync.DiscoveredSkill, unserved []string, byFile map[string]servedFile, next map[string]digest) (*Skill, string) { + for _, o := range unserved { + if strings.HasPrefix(o, s.RelPath+"/") { + return nil, fmt.Sprintf("contains %s, which is not served", o) + } + } + p, err := skillpkg.Load(s.SourcePath) + if err != nil { + return nil, err.Error() + } + base := "skill://" + escapePath(s.RelPath) + skill := &Skill{URI: base + "/SKILL.md", Frontmatter: p.Frontmatter} + files := make(map[string]servedFile, len(p.Files)) + for _, f := range p.Files { + sum, err := b.digest(f, next) + if err != nil { + return nil, err.Error() + } + uri := base + "/" + escapePath(f.Rel) + files[uri] = servedFile{dir: p.Dir, rel: f.Rel} + skill.Resources = append(skill.Resources, File{URI: uri, Digest: sum, Size: f.Size}) + } + for uri, f := range files { + byFile[uri] = f + } + return skill, "" +} + +// ponytail: size+mtime keys the digest cache, so a same-size edit within the +// filesystem's mtime granularity keeps the old digest until the next change. +func (b *Builder) digest(f skillpkg.File, next map[string]digest) (string, error) { + if d, ok := b.digests[f.Path]; ok && d.size == f.Size && d.mtime.Equal(f.ModTime) { + next[f.Path] = d + return d.sum, nil + } + sum, err := utils.FileHashFormatted(f.Path) + if err != nil { + return "", err + } + next[f.Path] = digest{size: f.Size, mtime: f.ModTime, sum: sum} + return sum, nil +} + +// Skill returns the served skill whose SKILL.md URI is uri. +func (c *Catalog) Skill(uri string) (*Skill, bool) { + key, ok := canonical(uri) + skill := c.bySkill[key] + return skill, ok && skill != nil +} + +// Read returns the content of a listed file. Only manifest files are served, +// and the read is confined to the skill directory. +func (c *Catalog) Read(uri string) ([]byte, error) { + key, ok := canonical(uri) + sf, listed := c.byFile[key] + if !ok || !listed { + return nil, errNotFound + } + root, err := os.OpenRoot(sf.dir) + if err != nil { + return nil, err + } + defer root.Close() + f, err := root.Open(sf.rel) + if err != nil { + return nil, err + } + defer f.Close() + return io.ReadAll(io.LimitReader(f, skillpkg.MaxBytes)) +} + +func escapePath(p string) string { + segs := strings.Split(p, "/") + for i, s := range segs { + segs[i] = url.PathEscape(s) + } + return strings.Join(segs, "/") +} + +// canonical decodes a skill:// URI and re-encodes it the way the catalog +// builds URIs. Empty, dot, and separator-bearing segments are rejected. +func canonical(uri string) (string, bool) { + rest, ok := strings.CutPrefix(uri, "skill://") + if !ok { + return "", false + } + segs := strings.Split(rest, "/") + for i, s := range segs { + d, err := url.PathUnescape(s) + if err != nil || d == "" || d == "." || d == ".." || strings.ContainsAny(d, "/\\\x00") { + return "", false + } + segs[i] = url.PathEscape(d) + } + return "skill://" + strings.Join(segs, "/"), true +} diff --git a/internal/skillserve/catalog_test.go b/internal/skillserve/catalog_test.go new file mode 100644 index 000000000..37e8f971f --- /dev/null +++ b/internal/skillserve/catalog_test.go @@ -0,0 +1,189 @@ +package skillserve + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/config" + "skillshare/internal/skillpkg" +) + +func writeFile(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func skillMD(name string) string { + return "---\nname: " + name + "\ndescription: Use when testing " + name + "\nmetadata:\n tags: [a, b]\n---\n# " + name + "\n" +} + +func find(c *Catalog, uri string) *Skill { + for _, s := range c.Skills { + if s.URI == uri { + return s + } + } + return nil +} + +func hasWarning(c *Catalog, substr string) bool { + for _, w := range c.Skipped { + if strings.Contains(w.String(), substr) { + return true + } + } + return false +} + +func TestBuild_PublishesFrontmatterAndCompleteManifest(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "_team/tools/pdf/SKILL.md"), skillMD("pdf")) + writeFile(t, filepath.Join(src, "_team/tools/pdf/references/FORMS.md"), "forms") + writeFile(t, filepath.Join(src, "_team/tools/pdf/.git/HEAD"), "ref") + + c, err := (&Builder{Source: src}).Build() + if err != nil { + t.Fatal(err) + } + s := find(c, "skill://_team/tools/pdf/SKILL.md") + if s == nil { + t.Fatalf("skill not published; skills=%v warnings=%v", c.Skills, c.Skipped) + } + if s.Frontmatter["name"] != "pdf" || s.Frontmatter["metadata"] == nil { + t.Errorf("frontmatter = %v, want full frontmatter", s.Frontmatter) + } + sum := sha256.Sum256([]byte("forms")) + want := map[string]File{ + "skill://_team/tools/pdf/SKILL.md": {Size: int64(len(skillMD("pdf")))}, + "skill://_team/tools/pdf/references/FORMS.md": {Size: 5, Digest: "sha256:" + hex.EncodeToString(sum[:])}, + } + if len(s.Resources) != len(want) { + t.Fatalf("resources = %+v, want SKILL.md and FORMS.md only", s.Resources) + } + for _, f := range s.Resources { + w, ok := want[f.URI] + if !ok || f.Size != w.Size || (w.Digest != "" && f.Digest != w.Digest) { + t.Errorf("unexpected resource %+v", f) + } + } +} + +func TestBuild_SkipsSkillWhoseNameDiffersFromDirectory(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "renamed/SKILL.md"), skillMD("original")) + + c, err := (&Builder{Source: src}).Build() + if err != nil { + t.Fatal(err) + } + if len(c.Skills) != 0 || !hasWarning(c, `does not match directory name "renamed"`) { + t.Errorf("skills=%v warnings=%v, want renamed skipped with a warning", c.Skills, c.Skipped) + } +} + +func TestBuild_AppliesTargetSelectionAndDisabledState(t *testing.T) { + src := t.TempDir() + for _, n := range []string{"keep", "drop", "off"} { + writeFile(t, filepath.Join(src, n, "SKILL.md"), skillMD(n)) + } + writeFile(t, filepath.Join(src, ".skillignore"), "off\n") + + c, err := (&Builder{Source: src, Target: "claude", Skills: &config.ResourceTargetConfig{Exclude: []string{"drop"}}}).Build() + if err != nil { + t.Fatal(err) + } + if len(c.Skills) != 1 || c.Skills[0].URI != "skill://keep/SKILL.md" { + t.Errorf("skills = %v, want only keep", c.Skills) + } +} + +func TestBuild_SkipsParentOfExcludedNestedSkill(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "suite/SKILL.md"), skillMD("suite")) + writeFile(t, filepath.Join(src, "suite/child/SKILL.md"), skillMD("child")) + + c, err := (&Builder{Source: src, Target: "claude", Skills: &config.ResourceTargetConfig{Exclude: []string{"suite__child"}}}).Build() + if err != nil { + t.Fatal(err) + } + if len(c.Skills) != 0 || !hasWarning(c, "suite/child") { + t.Errorf("skills=%v warnings=%v, want suite skipped because of excluded child", c.Skills, c.Skipped) + } +} + +func TestBuild_SkipsSkillOverFileLimit(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "big/SKILL.md"), skillMD("big")) + for i := range skillpkg.MaxFiles { + writeFile(t, filepath.Join(src, "big/refs", fmt.Sprintf("f%03d", i)), "") + } + + c, err := (&Builder{Source: src}).Build() + if err != nil { + t.Fatal(err) + } + if len(c.Skills) != 0 || !hasWarning(c, "512") { + t.Errorf("skills=%d warnings=%v, want big skipped over the file limit", len(c.Skills), c.Skipped) + } +} + +func TestBuild_RefreshesDigestWhenContentChanges(t *testing.T) { + src := t.TempDir() + ref := filepath.Join(src, "doc/notes.md") + writeFile(t, filepath.Join(src, "doc/SKILL.md"), skillMD("doc")) + writeFile(t, ref, "one") + b := &Builder{Source: src} + first, err := b.Build() + if err != nil { + t.Fatal(err) + } + writeFile(t, ref, "two!") + second, err := b.Build() + if err != nil { + t.Fatal(err) + } + digest := func(c *Catalog) string { + for _, f := range c.Skills[0].Resources { + if strings.HasSuffix(f.URI, "notes.md") { + return f.Digest + } + } + return "" + } + if digest(first) == digest(second) { + t.Error("digest did not change after the file changed") + } +} + +func TestRead_ServesOnlyManifestFilesInsideTheSkill(t *testing.T) { + src := t.TempDir() + outside := filepath.Join(t.TempDir(), "secret.txt") + writeFile(t, outside, "secret") + writeFile(t, filepath.Join(src, "doc/SKILL.md"), skillMD("doc")) + if err := os.Symlink(outside, filepath.Join(src, "doc/leak.txt")); err != nil { + t.Fatal(err) + } + c, err := (&Builder{Source: src}).Build() + if err != nil { + t.Fatal(err) + } + + if data, err := c.Read("skill://doc/SKILL.md"); err != nil || string(data) != skillMD("doc") { + t.Errorf("Read SKILL.md = %q, %v", data, err) + } + for _, uri := range []string{"skill://doc/leak.txt", "skill://doc/../doc/SKILL.md", "skill://doc/%2e%2e/doc/SKILL.md"} { + if _, err := c.Read(uri); err == nil { + t.Errorf("Read(%s) succeeded, want rejection", uri) + } + } +} diff --git a/internal/skillserve/server.go b/internal/skillserve/server.go new file mode 100644 index 000000000..2366093d9 --- /dev/null +++ b/internal/skillserve/server.go @@ -0,0 +1,220 @@ +package skillserve + +import ( + "context" + "crypto/subtle" + "errors" + "fmt" + "io" + "mime" + "net/http" + "path" + "strconv" + "sync" + "time" + "unicode/utf8" + + "github.com/modelcontextprotocol/go-sdk/jsonrpc" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// SEP-2640 methods. +const ( + methodList = "skills/list" + methodGet = "skills/get" +) + +const pageSize = 100 + +type listSkillsParams struct { + mcp.ParamsBase + Cursor string `json:"cursor,omitempty"` +} + +type listSkillsResult struct { + mcp.ResultBase + mcp.Cacheable + ResultType string `json:"resultType"` + Skills []*Skill `json:"skills"` + NextCursor string `json:"nextCursor,omitempty"` +} + +type getSkillParams struct { + mcp.ParamsBase + URI string `json:"uri"` +} + +type getSkillResult struct { + mcp.ResultBase + mcp.Cacheable + ResultType string `json:"resultType"` + Skill *Skill `json:"skill"` +} + +// Options configures NewServer. +type Options struct { + Version string + // Warn receives each skip warning when it first appears. + Warn io.Writer + // Refresh is how long a catalog is reused before the source is read again; + // it is also the ttlMs hint. Zero rebuilds on every request. + Refresh time.Duration +} + +type service struct { + b *Builder + opts Options + + mu sync.Mutex + cat *Catalog + built time.Time + warned map[string]bool +} + +// NewServer returns a read-only MCP server for the skills b selects. The first +// catalog is built here, so source errors and initial warnings surface at once. +func NewServer(b *Builder, opts Options) (*mcp.Server, error) { + if opts.Warn == nil { + opts.Warn = io.Discard + } + svc := &service{b: b, opts: opts} + if _, err := svc.catalog(); err != nil { + return nil, err + } + srv := mcp.NewServer(&mcp.Implementation{Name: "skillshare", Version: opts.Version}, &mcp.ServerOptions{ + Capabilities: &mcp.ServerCapabilities{ + Resources: &mcp.ResourceCapabilities{}, + Extensions: map[string]any{extensionID: map[string]any{}}, + }, + }) + srv.AddResourceTemplate(&mcp.ResourceTemplate{Name: "skill-file", URITemplate: "skill://{+path}"}, svc.read) + if err := mcp.AddReceivingCustomMethod(srv, methodList, svc.list); err != nil { + return nil, err + } + if err := mcp.AddReceivingCustomMethod(srv, methodGet, svc.get); err != nil { + return nil, err + } + svc.addTools(srv) + return srv, nil +} + +// HTTPHandler serves srv over Streamable HTTP. A non-empty token must be sent +// as a bearer token on every request. +func HTTPHandler(srv *mcp.Server, token string) http.Handler { + h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, &mcp.StreamableHTTPOptions{Stateless: true}) + if token == "" { + return h + } + want := []byte("Bearer " + token) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), want) != 1 { + w.Header().Set("WWW-Authenticate", "Bearer") + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + h.ServeHTTP(w, r) + }) +} + +func (s *service) catalog() (*Catalog, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.cat != nil && time.Since(s.built) < s.opts.Refresh { + return s.cat, nil + } + c, err := s.b.Build() + if err != nil { + return nil, err + } + seen := make(map[string]bool, len(c.Skipped)) + for _, skip := range c.Skipped { + w := skip.String() + seen[w] = true + if !s.warned[w] { + fmt.Fprintln(s.opts.Warn, "warning: "+w) + } + } + s.cat, s.built, s.warned = c, time.Now(), seen + return c, nil +} + +func (s *service) cacheable() mcp.Cacheable { + return mcp.Cacheable{TTLMs: int(s.opts.Refresh.Milliseconds()), CacheScope: "private"} +} + +func invalidParams(msg string) error { + return &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: msg} +} + +func (s *service) list(_ context.Context, _ *mcp.ServerSession, p *listSkillsParams) (*listSkillsResult, error) { + c, err := s.catalog() + if err != nil { + return nil, err + } + start := 0 + if p != nil && p.Cursor != "" { + n, err := strconv.Atoi(p.Cursor) + if err != nil || n < 0 || n > len(c.Skills) { + return nil, invalidParams("invalid cursor") + } + start = n + } + end := min(start+pageSize, len(c.Skills)) + res := &listSkillsResult{Cacheable: s.cacheable(), ResultType: "complete", Skills: c.Skills[start:end]} + if end < len(c.Skills) { + res.NextCursor = strconv.Itoa(end) + } + return res, nil +} + +func (s *service) get(_ context.Context, _ *mcp.ServerSession, p *getSkillParams) (*getSkillResult, error) { + c, err := s.catalog() + if err != nil { + return nil, err + } + if p == nil { + return nil, invalidParams("missing uri") + } + skill, ok := c.Skill(p.URI) + if !ok { + return nil, invalidParams("skill not found: " + p.URI) + } + return &getSkillResult{Cacheable: s.cacheable(), ResultType: "complete", Skill: skill}, nil +} + +func (s *service) read(_ context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { + c, err := s.catalog() + if err != nil { + return nil, err + } + uri := req.Params.URI + data, err := c.Read(uri) + if errors.Is(err, errNotFound) { + return nil, mcp.ResourceNotFoundError(uri) + } + if err != nil { + return nil, err + } + text := utf8.Valid(data) + content := &mcp.ResourceContents{URI: uri, MIMEType: mimeType(uri, text)} + if text { + content.Text = string(data) + } else { + content.Blob = data + } + return &mcp.ReadResourceResult{Cacheable: s.cacheable(), Contents: []*mcp.ResourceContents{content}}, nil +} + +func mimeType(uri string, text bool) string { + ext := path.Ext(uri) + if ext == ".md" { + return "text/markdown" + } + if t := mime.TypeByExtension(ext); t != "" { + return t + } + if text { + return "text/plain" + } + return "application/octet-stream" +} diff --git a/internal/skillserve/server_test.go b/internal/skillserve/server_test.go new file mode 100644 index 000000000..3d536276b --- /dev/null +++ b/internal/skillserve/server_test.go @@ -0,0 +1,183 @@ +package skillserve + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "github.com/modelcontextprotocol/go-sdk/jsonrpc" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func connect(t *testing.T, src string) *mcp.ClientSession { + t.Helper() + return connectWith(t, src, nil) +} + +func connectWith(t *testing.T, src string, opts *mcp.ClientOptions) *mcp.ClientSession { + t.Helper() + ctx := context.Background() + srv, err := NewServer(&Builder{Source: src}, Options{Version: "test", Warn: io.Discard}) + if err != nil { + t.Fatal(err) + } + ct, st := mcp.NewInMemoryTransports() + ss, err := srv.Connect(ctx, st, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ss.Close() }) + client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "v1"}, opts) + if err := mcp.AddSendingCustomMethod[*listSkillsParams, *listSkillsResult](client, methodList); err != nil { + t.Fatal(err) + } + if err := mcp.AddSendingCustomMethod[*getSkillParams, *getSkillResult](client, methodGet); err != nil { + t.Fatal(err) + } + cs, err := client.Connect(ctx, ct, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cs.Close() }) + return cs +} + +func listSkills(t *testing.T, cs *mcp.ClientSession, cursor string) *listSkillsResult { + t.Helper() + res, err := mcp.CallCustomMethod[*listSkillsParams, *listSkillsResult](context.Background(), cs, methodList, &listSkillsParams{Cursor: cursor}) + if err != nil { + t.Fatal(err) + } + return res +} + +func TestServer_DeclaresSkillsExtension(t *testing.T) { + cs := connect(t, t.TempDir()) + caps := cs.InitializeResult().Capabilities + if _, ok := caps.Extensions[extensionID]; !ok || caps.Resources == nil { + t.Errorf("capabilities = %+v, want resources and %s", caps, extensionID) + } +} + +func TestServer_ListPaginatesWholeEntries(t *testing.T) { + src := t.TempDir() + for i := range pageSize + 1 { + name := fmt.Sprintf("s%03d", i) + writeFile(t, filepath.Join(src, name, "SKILL.md"), skillMD(name)) + } + cs := connect(t, src) + + first := listSkills(t, cs, "") + if len(first.Skills) != pageSize || first.NextCursor == "" || first.ResultType != "complete" || first.CacheScope == "" { + t.Fatalf("first page: %d skills, cursor %q, resultType %q, cacheScope %q", len(first.Skills), first.NextCursor, first.ResultType, first.CacheScope) + } + second := listSkills(t, cs, first.NextCursor) + if len(second.Skills) != 1 || second.NextCursor != "" { + t.Errorf("second page: %d skills, cursor %q, want the last skill and no cursor", len(second.Skills), second.NextCursor) + } +} + +func TestServer_GetUnknownSkillIsInvalidParams(t *testing.T) { + cs := connect(t, t.TempDir()) + _, err := mcp.CallCustomMethod[*getSkillParams, *getSkillResult](context.Background(), cs, methodGet, &getSkillParams{URI: "skill://missing/SKILL.md"}) + var rpcErr *jsonrpc.Error + if !errors.As(err, &rpcErr) || rpcErr.Code != jsonrpc.CodeInvalidParams { + t.Errorf("err = %v, want -32602", err) + } +} + +func TestServer_ReadsSkillFileAsMarkdown(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "doc/SKILL.md"), skillMD("doc")) + cs := connect(t, src) + + res, err := cs.ReadResource(context.Background(), &mcp.ReadResourceParams{URI: "skill://doc/SKILL.md"}) + if err != nil { + t.Fatal(err) + } + if len(res.Contents) != 1 || res.Contents[0].Text != skillMD("doc") || res.Contents[0].MIMEType != "text/markdown" { + t.Errorf("contents = %+v", res.Contents) + } +} + +func TestHTTPHandler_RequiresBearerToken(t *testing.T) { + srv, err := NewServer(&Builder{Source: t.TempDir()}, Options{}) + if err != nil { + t.Fatal(err) + } + h := HTTPHandler(srv, "s3cret") + for _, auth := range []string{"", "Bearer wrong"} { + req := httptest.NewRequest(http.MethodPost, "http://127.0.0.1/", strings.NewReader(`{}`)) + req.Header.Set("Authorization", auth) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Errorf("Authorization %q: status %d, want 401", auth, rec.Code) + } + } +} + +func TestServer_SeesNewSkillWithoutRestart(t *testing.T) { + src := t.TempDir() + cs := connect(t, src) + if got := listSkills(t, cs, ""); len(got.Skills) != 0 { + t.Fatalf("got %d skills, want 0", len(got.Skills)) + } + writeFile(t, filepath.Join(src, "late/SKILL.md"), skillMD("late")) + + res, err := mcp.CallCustomMethod[*getSkillParams, *getSkillResult](context.Background(), cs, methodGet, &getSkillParams{URI: "skill://late/SKILL.md"}) + if err != nil || res.Skill == nil || res.Skill.Frontmatter["name"] != "late" { + t.Errorf("get late = %+v, %v", res, err) + } +} + +func callTool(t *testing.T, cs *mcp.ClientSession, name string, args map[string]any) (string, bool) { + t.Helper() + res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args}) + if err != nil { + t.Fatal(err) + } + return res.Content[0].(*mcp.TextContent).Text, res.IsError +} + +func TestServer_ToolsListAndReadSkillsForClientsWithoutTheExtension(t *testing.T) { + src := t.TempDir() + writeFile(t, filepath.Join(src, "pdf", "SKILL.md"), skillMD("pdf")) + writeFile(t, filepath.Join(src, "pdf", "references", "guide.md"), "# Guide\n") + writeFile(t, filepath.Join(src, "review", "SKILL.md"), skillMD("review")) + cs := connect(t, src) + + if tools, err := cs.ListTools(context.Background(), nil); err != nil || len(tools.Tools) != 2 { + t.Fatalf("tools/list = %v, %v; want list_skills and read_skill", tools, err) + } + list, _ := callTool(t, cs, "list_skills", map[string]any{"query": "PDF"}) + if !strings.Contains(list, "skill://pdf/SKILL.md") || strings.Contains(list, "review") { + t.Errorf("list_skills query=PDF:\n%s", list) + } + body, _ := callTool(t, cs, "read_skill", map[string]any{"uri": "skill://pdf/SKILL.md"}) + if !strings.Contains(body, "# pdf") || !strings.Contains(body, "skill://pdf/references/guide.md") { + t.Errorf("read_skill SKILL.md should return the body and list the other files:\n%s", body) + } + if msg, isErr := callTool(t, cs, "read_skill", map[string]any{"uri": "skill://pdf/../review/SKILL.md"}); !isErr { + t.Errorf("read_skill outside the skill = %q, want a tool error", msg) + } +} + +func TestServer_HidesToolsFromClientsWithTheExtension(t *testing.T) { + caps := &mcp.ClientCapabilities{} + caps.AddExtension(extensionID, map[string]any{}) + cs := connectWith(t, t.TempDir(), &mcp.ClientOptions{Capabilities: caps}) + res, err := cs.ListTools(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + if len(res.Tools) != 0 { + t.Errorf("tools = %d, want none: the client loads skills natively", len(res.Tools)) + } +} diff --git a/internal/skillserve/tools.go b/internal/skillserve/tools.go new file mode 100644 index 000000000..2b9fce820 --- /dev/null +++ b/internal/skillserve/tools.go @@ -0,0 +1,117 @@ +package skillserve + +import ( + "context" + "errors" + "fmt" + "strings" + "unicode/utf8" + + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// Tools for clients without the Skills extension, which is most of them: the +// model lists and reads skills itself. Content read this way is ordinary text, +// not a loaded skill, so the client's own skill approval does not apply. +// A client that declares the extension sees no tools and loads skills natively. + +// listLimit caps one list_skills answer so a large catalog does not flood the +// model's context; the query narrows it. +const listLimit = 200 + +type listToolInput struct { + Query string `json:"query,omitempty" jsonschema:"Only skills whose name or description contains this text, ignoring case"` +} + +type readToolInput struct { + URI string `json:"uri" jsonschema:"A skill:// URI from list_skills, or one of the files read_skill lists for a skill"` +} + +func (s *service) addTools(srv *mcp.Server) { + mcp.AddTool(srv, &mcp.Tool{ + Name: "list_skills", + Description: "List the available skills: name, when to use it, and its URI. Read a skill with read_skill before following it.", + }, s.listTool) + mcp.AddTool(srv, &mcp.Tool{ + Name: "read_skill", + Description: "Read a skill's SKILL.md, or one of its other files, by skill:// URI. Reading SKILL.md also lists the skill's other files.", + }, s.readTool) + srv.AddReceivingMiddleware(hideToolsFromNativeClients) +} + +// hideToolsFromNativeClients leaves a client that declares the Skills +// extension without the tools, so it does not see each skill twice. +func hideToolsFromNativeClients(next mcp.MethodHandler) mcp.MethodHandler { + return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) { + res, err := next(ctx, method, req) + if r, ok := req.(*mcp.ListToolsRequest); ok && err == nil { + if caps := r.ClientCapabilities(); caps != nil { + if _, native := caps.Extensions[extensionID]; native { + res.(*mcp.ListToolsResult).Tools = []*mcp.Tool{} + } + } + } + return res, err + } +} + +func textResult(text string) *mcp.CallToolResult { + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: text}}} +} + +func (s *service) listTool(_ context.Context, _ *mcp.CallToolRequest, in listToolInput) (*mcp.CallToolResult, any, error) { + c, err := s.catalog() + if err != nil { + return nil, nil, err + } + query := strings.ToLower(in.Query) + var b strings.Builder + n := 0 + for _, skill := range c.Skills { + name, _ := skill.Frontmatter["name"].(string) + desc, _ := skill.Frontmatter["description"].(string) + if query != "" && !strings.Contains(strings.ToLower(name+"\n"+desc), query) { + continue + } + if n++; n <= listLimit { + fmt.Fprintf(&b, "- %s: %s\n %s\n", name, strings.Join(strings.Fields(desc), " "), skill.URI) + } + } + switch { + case n == 0: + return textResult("No skills match."), nil, nil + case n > listLimit: + fmt.Fprintf(&b, "\n%d more skills match; pass a query to narrow the list.\n", n-listLimit) + } + return textResult(b.String()), nil, nil +} + +func (s *service) readTool(_ context.Context, _ *mcp.CallToolRequest, in readToolInput) (*mcp.CallToolResult, any, error) { + c, err := s.catalog() + if err != nil { + return nil, nil, err + } + data, err := c.Read(in.URI) + if errors.Is(err, errNotFound) { + return nil, nil, fmt.Errorf("no skill file %s; list_skills gives the skill URIs", in.URI) + } + if err != nil { + return nil, nil, err + } + if !utf8.Valid(data) { + return nil, nil, fmt.Errorf("%s is a binary file", in.URI) + } + text := string(data) + if skill, ok := c.Skill(in.URI); ok && len(skill.Resources) > 1 { + var b strings.Builder + b.WriteString(text) + b.WriteString("\n\n---\nOther files in this skill (read them with read_skill):\n") + for _, f := range skill.Resources { + if f.URI != skill.URI { + fmt.Fprintf(&b, "- %s\n", f.URI) + } + } + text = b.String() + } + return textResult(text), nil, nil +} diff --git a/internal/sync/filter.go b/internal/sync/filter.go index 4e3cce374..ab103785d 100644 --- a/internal/sync/filter.go +++ b/internal/sync/filter.go @@ -194,6 +194,18 @@ func suggestFlatNames(pattern string, skills []DiscoveredSkill) []string { return names } +// SelectTargetSkills returns the source skills a target receives: enabled +// skills that pass its include/exclude filters and whose frontmatter targets +// name it or declare none. +func SelectTargetSkills(skills []DiscoveredSkill, targetName string, sc config.ResourceTargetConfig) ([]DiscoveredSkill, error) { + enabled := slices.DeleteFunc(slices.Clone(skills), func(s DiscoveredSkill) bool { return s.Disabled }) + filtered, err := FilterSkills(enabled, sc.Include, sc.Exclude) + if err != nil { + return nil, err + } + return FilterSkillsByTarget(filtered, targetName), nil +} + // FilterSkillsByTarget removes skills whose Targets field does not include // the given target name. Skills with nil Targets (no field declared) pass // through unconditionally. diff --git a/internal/sync/filter_target_test.go b/internal/sync/filter_target_test.go index 34f6ad7db..5d473db5b 100644 --- a/internal/sync/filter_target_test.go +++ b/internal/sync/filter_target_test.go @@ -3,9 +3,24 @@ package sync import ( "testing" + "skillshare/internal/config" "skillshare/internal/resource" ) +func TestSelectTargetSkills_AppliesDisabledFiltersAndTargets(t *testing.T) { + skills := []DiscoveredSkill{ + {FlatName: "keep"}, + {FlatName: "off", Disabled: true}, + {FlatName: "dropped"}, + {FlatName: "cursor-only", Targets: []string{"cursor"}}, + } + got, err := SelectTargetSkills(skills, "claude", config.ResourceTargetConfig{Exclude: []string{"dropped"}}) + if err != nil { + t.Fatal(err) + } + assertFlatNames(t, got, []string{"keep"}) +} + func TestFilterSkillsByTarget_NilPassesThrough(t *testing.T) { skills := []DiscoveredSkill{ {FlatName: "no-targets", Targets: nil}, diff --git a/internal/sync/target_naming.go b/internal/sync/target_naming.go index 950778a36..8f4947213 100644 --- a/internal/sync/target_naming.go +++ b/internal/sync/target_naming.go @@ -7,6 +7,7 @@ import ( "strings" "skillshare/internal/config" + "skillshare/internal/skillpkg" "skillshare/internal/utils" ) @@ -54,11 +55,10 @@ func (r *TargetSkillResolution) UnmatchedIncludeWarnings() []string { // ResolveTargetSkillsForTarget applies a target's filters and target_naming // policy to discovered skills and returns the effective target-visible skills. func ResolveTargetSkillsForTarget(targetName string, sc config.ResourceTargetConfig, allSkills []DiscoveredSkill) (*TargetSkillResolution, error) { - filtered, err := FilterSkills(allSkills, sc.Include, sc.Exclude) + filtered, err := SelectTargetSkills(allSkills, targetName, sc) if err != nil { return nil, fmt.Errorf("failed to apply filters for target %s: %w", targetName, err) } - filtered = FilterSkillsByTarget(filtered, targetName) naming := config.EffectiveTargetNaming(sc.TargetNaming) result := &TargetSkillResolution{ @@ -159,29 +159,5 @@ func (r *TargetSkillResolution) LegacyFlatNames() map[string]ResolvedTargetSkill } func validateStandardTargetSkill(skill DiscoveredSkill, skillName string) string { - if skillName == "" { - return "SKILL.md is missing a name" - } - if len(skillName) > 64 { - return fmt.Sprintf("SKILL.md name %q is longer than 64 characters", skillName) - } - if strings.HasPrefix(skillName, "-") || strings.HasSuffix(skillName, "-") { - return fmt.Sprintf("SKILL.md name %q cannot start or end with '-'", skillName) - } - if strings.Contains(skillName, "--") { - return fmt.Sprintf("SKILL.md name %q cannot contain consecutive hyphens", skillName) - } - for _, r := range skillName { - if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' { - continue - } - return fmt.Sprintf("SKILL.md name %q must use only lowercase letters, numbers, and hyphens", skillName) - } - - dirName := filepath.Base(filepath.Clean(skill.SourcePath)) - if skillName != dirName { - return fmt.Sprintf("SKILL.md name %q does not match directory name %q", skillName, dirName) - } - - return "" + return skillpkg.ValidateName(skillName, filepath.Base(filepath.Clean(skill.SourcePath))) } diff --git a/internal/utils/frontmatter.go b/internal/utils/frontmatter.go index 870924829..fe2584279 100644 --- a/internal/utils/frontmatter.go +++ b/internal/utils/frontmatter.go @@ -211,6 +211,19 @@ func extractFrontmatterRaw(filePath string) string { return strings.Join(lines, "\n") } +// ParseFrontmatterMap returns the complete YAML frontmatter of SKILL.md content. +func ParseFrontmatterMap(content []byte) (map[string]any, error) { + raw := extractFrontmatterRawFromBytes(content) + if raw == "" { + return nil, fmt.Errorf("no frontmatter") + } + var fm map[string]any + if err := yaml.Unmarshal([]byte(raw), &fm); err != nil { + return nil, fmt.Errorf("invalid frontmatter: %w", err) + } + return fm, nil +} + // ParseFrontmatterFields reads a SKILL.md file once and returns the values of // multiple frontmatter fields. This avoids opening the same file repeatedly // when multiple fields are needed (e.g. description + license). diff --git a/skills/skillshare/SKILL.md b/skills/skillshare/SKILL.md index 8b39521bd..40282a40f 100644 --- a/skills/skillshare/SKILL.md +++ b/skills/skillshare/SKILL.md @@ -33,8 +33,8 @@ Check `skillshare --help` if the installed version differs from these before editing MCP settings or importing native configurations. Its Agent notes cover what is specific to Claude Code, Codex, OpenCode and Pi: scopes and files, names and credentials they refuse, Pi's built-in MCP and `piOptions`, OMP's native MCP and preserved enable/disable lists, the portable `tools` policy, - upgrading Pi settings from 0.22, turning a global server off in one project, and `mcp.projects` for many folders from - one config. + upgrading Pi settings from 0.22, turning a global server off in one project, `mcp.projects` for many folders from + one config, and `mcp serve` for Agents that cannot reach the synced skill folders. - Plugins keep their native components together. Read [plugins.md](references/plugins.md) for installation, import, sync selection, updates, and native compatibility limits across Claude, Codex, Cursor, Antigravity, Pi, OMP, and OpenCode, including Pi packages from pi.dev diff --git a/skills/skillshare/references/mcp.md b/skills/skillshare/references/mcp.md index 073514faf..d4caab996 100644 --- a/skills/skillshare/references/mcp.md +++ b/skills/skillshare/references/mcp.md @@ -22,6 +22,8 @@ skillshare mcp restore BACKUP_ID --dry-run --json # Preview entry-level rest skillshare mcp restore BACKUP_ID --no-tui # Apply restoration; source stays unchanged skillshare mcp check --json # Static check: variables, commands, DNS, sync state skillshare mcp check --live --timeout 30s --json # Also start/call each server: serverInfo, protocol, tools +skillshare mcp serve [--target NAME] [--http ADDR] # Serve skills read-only over MCP (SEP-2640) +skillshare mcp serve --check [--target NAME] # List skills serve would skip, then exit ``` ## Automation rules @@ -50,6 +52,17 @@ skillshare mcp check --live --timeout 30s --json # Also start/call each serv its `env`) and POSTs to each remote one, skipping servers with a static error. A 401 is a warning with the resource metadata URL; it never signs in. Use it only for trusted servers. `--json` adds `live: {protocolVersion, serverInfo, tools, toolNames}`. +- `mcp serve` serves skills to Agents that cannot reach the synced folders (VMs, MCP + gateways): stdio by default, global unless `-p`. `--target NAME` applies that target's + filters. Skipped skills (name not matching its directory, over 512 files/16 MiB) are + listed on stderr; `--check` lists them without serving. `--http` on a non-loopback address requires `SKILLSHARE_MCP_TOKEN`. + Do not connect local Agents that already sync skills; they would see each skill twice. + Connect one with `mcp add skillshare --target CLIENT --sync -- skillshare mcp serve`, or a + remote `url` with `bearerToken: {fromEnv: SKILLSHARE_MCP_TOKEN}`. Agents with the Skills + extension load skills natively; as of October 2026 Codex, Cursor, VS Code, Goose and Pi + lack it and Claude Code's is off by default, so the server also offers `list_skills` + (`query` filters) and `read_skill` tools, hidden from clients that declare the extension. Verify the server with + `npx @modelcontextprotocol/inspector --cli skillshare mcp serve --method skills/list --verify`. - Noninteractive `import` without a name only lists candidates. Use `--replace` only when replacing is intended. - An `update` with the message `same settings, laid out one field per line` is a diff --git a/tests/integration/completion_test.go b/tests/integration/completion_test.go index bada3ba7d..f14125467 100644 --- a/tests/integration/completion_test.go +++ b/tests/integration/completion_test.go @@ -70,11 +70,11 @@ func TestCompletion_MCPCheck_AllShells(t *testing.T) { defer sb.Cleanup() for shell, subcommands := range map[string]string{ - "bash": "add check edit import list remove restore", - "zsh": "(add check edit import list remove restore)", - "fish": "-a 'add check edit import list remove restore'", - "powershell": "@{ Name = 'edit'; Desc = 'MCP edit' }", - "nushell": "[add check edit import list remove restore]", + "bash": "add check edit import list remove restore serve", + "zsh": "(add check edit import list remove restore serve)", + "fish": "-a 'add check edit import list remove restore serve'", + "powershell": "@{ Name = 'serve'; Desc = 'MCP serve' }", + "nushell": "[add check edit import list remove restore serve]", } { result := sb.RunCLI("completion", shell) result.AssertSuccess(t) diff --git a/tests/integration/mcp_serve_test.go b/tests/integration/mcp_serve_test.go new file mode 100644 index 000000000..b6ff02962 --- /dev/null +++ b/tests/integration/mcp_serve_test.go @@ -0,0 +1,105 @@ +//go:build !online + +package integration + +import ( + "bufio" + "bytes" + "fmt" + "os" + "os/exec" + "strings" + "testing" + + "skillshare/internal/testutil" +) + +const serveMeta = `"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}` + +func TestMCPServe_StdioListsValidSkills(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + sb.CreateSkill("pdf", map[string]string{"SKILL.md": "---\nname: pdf\ndescription: Use when editing PDFs\n---\n# PDF\n"}) + sb.CreateSkill("renamed", map[string]string{"SKILL.md": "---\nname: original\ndescription: Use when testing\n---\n# Renamed\n"}) + + // The server drops requests still in flight when stdin closes, so keep it + // open until both responses arrive, as a spawning gateway does. + cmd := exec.Command(sb.BinaryPath, "mcp", "serve", "-g") + cmd.Env = append(os.Environ(), "HOME="+sb.Home, "SKILLSHARE_CONFIG="+sb.ConfigPath) + var stderr bytes.Buffer + cmd.Stderr = &stderr + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + fmt.Fprintln(stdin, `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{`+serveMeta+`}}`) + fmt.Fprintln(stdin, `{"jsonrpc":"2.0","id":2,"method":"skills/list","params":{`+serveMeta+`}}`) + scanner := bufio.NewScanner(stdout) + var out strings.Builder + for range 2 { + if !scanner.Scan() { + t.Fatalf("missing response: %v\nstderr: %s", scanner.Err(), stderr.String()) + } + out.WriteString(scanner.Text()) + } + stdin.Close() + if err := cmd.Wait(); err != nil { + t.Fatalf("serve exited with %v\nstderr: %s", err, stderr.String()) + } + + for _, want := range []string{`"io.modelcontextprotocol/skills"`, `"uri":"skill://pdf/SKILL.md"`} { + if !strings.Contains(out.String(), want) { + t.Errorf("responses missing %s:\n%s", want, out.String()) + } + } + if strings.Contains(out.String(), "skill://renamed") { + t.Errorf("renamed skill was served:\n%s", out.String()) + } + if want := `skipped renamed: SKILL.md name "original" does not match directory name "renamed"`; !strings.Contains(stderr.String(), want) { + t.Errorf("stderr missing %q:\n%s", want, stderr.String()) + } +} + +func TestMCPServe_CheckListsSkippedSkillsWithoutServing(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + sb.CreateSkill("pdf", map[string]string{"SKILL.md": "---\nname: pdf\ndescription: Use when editing PDFs\n---\n# PDF\n"}) + sb.CreateSkill("renamed", map[string]string{"SKILL.md": "---\nname: original\ndescription: Use when testing\n---\n# Renamed\n"}) + + r := sb.RunCLI("mcp", "serve", "--check", "-g") + + r.AssertSuccess(t) + r.AssertRowContains(t, "renamed", `SKILL.md name "original" does not match directory name "renamed"`) + r.AssertOutputContains(t, "1 skill served, 1 skipped") +} + +func TestMCPServe_RefusesUnauthenticatedNetworkListener(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + + r := sb.RunCLI("mcp", "serve", "--http", "0.0.0.0:0") + + r.AssertFailure(t) + r.AssertAnyOutputContains(t, "SKILLSHARE_MCP_TOKEN") +} + +func TestMCPServe_RejectsUnknownTarget(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + + r := sb.RunCLI("mcp", "serve", "--target", "nope") + + r.AssertFailure(t) + r.AssertAnyOutputContains(t, `unknown target "nope"`) +} diff --git a/website/docs/reference/commands/mcp.md b/website/docs/reference/commands/mcp.md index b43dc4353..058bf5095 100644 --- a/website/docs/reference/commands/mcp.md +++ b/website/docs/reference/commands/mcp.md @@ -25,6 +25,9 @@ skillshare mcp check --live --timeout 30s skillshare mcp remove docs --sync skillshare mcp remove docs --keep-files skillshare mcp restore BACKUP_ID --dry-run +skillshare mcp serve +skillshare mcp serve --target claude --http 127.0.0.1:8765 +skillshare mcp serve --check skillshare sync mcp --dry-run --json skillshare sync mcp skillshare sync --all @@ -32,7 +35,7 @@ skillshare sync --all | Option | Meaning | |---|---| -| `--target CLIENT` | Receiving client; repeat to select multiple clients. `--target none` keeps the server in Skillshare without writing it to any client. See [below](#keep-a-server-without-syncing-it) | +| `--target CLIENT` | Receiving client; repeat to select multiple clients. `--target none` keeps the server in Skillshare without writing it to any client. See [below](#keep-a-server-without-syncing-it). With `serve`, `--target NAME` names a skills target instead; see [below](#serve-skills-over-mcp) | | `--url URL` | Streamable HTTP endpoint for `add` | | `-- command args...` | Local executable and literal arguments for `add` | | `--disabled` | Project mode, with `add`: turn off a server the Agent's global config defines. See [below](#turn-off-a-global-server-in-one-project) | @@ -49,6 +52,8 @@ skillshare sync --all | `--no-dns` | With `check`: skip the host lookup of remote servers. See [below](#check-servers-before-an-agent-starts-them) | | `--live` | With `check`: also start each local server and call each remote one. See [below](#probe-servers-live) | | `--timeout DURATION` | With `check --live`: time limit for each server's probe, such as `30s`; default `10s` | +| `--http ADDR` | With `serve`: listen for Streamable HTTP on `ADDR` instead of using stdio. See [below](#serve-skills-over-mcp) | +| `--check` | With `serve`: list the skills it would skip and why, then exit without serving | | `--no-tui` | Disable interactive menus; also disabled by `tui: false`, `--json`, or non-terminal input/output | | `--revision ID` | Require a matching preview for add/import/remove or `sync mcp` | | `--global`, `-g` | Use global Skillshare configuration | @@ -765,6 +770,94 @@ and writes no files until you choose for that entry: - Replace it with the source definition: **Replace with source** in the dashboard, or `--replace` on import. +## Serve skills over MCP {#serve-skills-over-mcp} + +```bash +skillshare mcp serve # stdio, every enabled skill +skillshare mcp serve --target claude # only the skills the claude target selects +SKILLSHARE_MCP_TOKEN=change-me skillshare mcp serve --http 0.0.0.0:8765 +``` + +`mcp serve` is a read-only MCP server for an Agent that cannot reach the folder +your skills sync to, such as one on a disposable VM or behind an MCP gateway. It +implements the [Skills extension](https://modelcontextprotocol.io/seps/2640-skills-extension) +(`io.modelcontextprotocol/skills`, SEP-2640): `skills/list`, `skills/get` and +`resources/read`. Each skill is one entry whose URI follows its source path, such as +`skill://_team/tools/pdf/SKILL.md`, with its full frontmatter and every file with a +`sha256` digest and size. Agents on your own machine already receive skills through +`sync`; connecting them to `mcp serve` as well shows each skill twice. + +Most Agents do not support the Skills extension yet (see below), so the server also offers +two tools: `list_skills` lists names, descriptions and URIs (`query` narrows them; one +answer lists at most 200), and `read_skill` reads a `SKILL.md` or another file of a skill, +and for a `SKILL.md` lists the skill's other files. Any Agent that uses MCP tools can read +skills this way, including through a gateway that passes tools on. A client that declares +the Skills extension loads skills natively and is not offered the tools, so it does not +see each skill twice. Content read through a tool is ordinary text to the Agent: its own +skill approval does not apply. + +- **Selection.** Without `--target`, every enabled skill is served. `--target NAME` + applies that target's `include`/`exclude` filters and frontmatter `targets`, whatever + its sync mode; skills always come from the source. A target with skills turned off is + an error. +- **Skipped skills.** A skill is skipped, with a warning on stderr, when its `SKILL.md` + `name` breaks the Agent Skills naming rules or differs from its directory name (for + example after `install --name`), when it has no description, when it has more than 512 + files or 16 MiB, or when it contains a nested skill that is not served. + `skillshare mcp serve --check` lists those skills and their reasons, with the same + selection flags, and exits without serving. +- **Changes.** The source is read again at most every 5 seconds, so `install`, + `update`, `enable` and `disable` show up without a restart. Results carry + `ttlMs: 5000`. +- **Scope.** Global by default, wherever the server is started. `-p` serves the project + in the current directory. +- **Transport.** stdio by default, for a gateway or Agent that starts the command. + `--http ADDR` serves Streamable HTTP. A non-loopback address requires + `SKILLSHARE_MCP_TOKEN`; when it is set, every request must send + `Authorization: Bearer `. +- **Safety.** Only files in a skill's manifest can be read, and reads stay inside the + skill directory. Links and `.git` are neither listed nor served. Nothing is executed or + written. + +To connect an Agent, add the server like any other and sync it. On the machine that +runs the Agent: + +```bash +skillshare mcp add skillshare --target codex --sync -- skillshare mcp serve --target codex +``` + +In the dashboard, **Add server** → **Skillshare** builds the same command (with `-p` in +project mode) from a choice of skills; tick the Agent, save and sync. Editing that server +opens the same tab. + +For an Agent on another machine, run `mcp serve --http` where the skills are and point a +remote server at it. Keep the token in an environment variable: + +```yaml +mcp: + servers: + skillshare: + url: http://skills-host:8765/ + bearerToken: { fromEnv: SKILLSHARE_MCP_TOKEN } + targets: [codex] +``` + +Loading skills natively needs the Skills extension. As of October 2026 the common coding +Agents do not have it yet, so they use the tools: Codex, Cursor, VS Code, Goose and Pi have no support, and Claude Code includes +support that is not switched on by default. Only a few clients such as mcpc, fast-agent and +MCP Inspector do, some in part. The SEP's list of prototype hosts, such as a Codex fork, +does not mean the released Agents support it. The +[extension support matrix](https://modelcontextprotocol.io/extensions/client-matrix) lists +the current clients. + +To check the server itself, MCP Inspector 2.6.0 or later reads every skill, compares its +frontmatter and checks each file's digest: + +```bash +npx @modelcontextprotocol/inspector --cli skillshare mcp serve --method skills/list --verify +``` + + ## Safety and limitations - JSONC comments and unrelated settings are preserved. Changed owned entries