mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
Merge pull request #431 from runkids/runkids/428-mcp-serve-skills
feat(mcp): serve skills over MCP (SEP-2640) with a tool fallback
This commit is contained in:
@@ -6,20 +6,25 @@
|
||||
set -euo pipefail
|
||||
|
||||
PREFIX="$HOME/.local/agent-clis"
|
||||
# bin → npm package
|
||||
# bin → npm package, optionally @version. A pinned package is reinstalled when the
|
||||
# volume holds another version; an unpinned one is installed once and left alone.
|
||||
declare -A PACKAGES=(
|
||||
[claude]="@anthropic-ai/claude-code"
|
||||
[codex]="@openai/codex"
|
||||
[pi]="@earendil-works/pi-coding-agent"
|
||||
[pi]="@earendil-works/pi-coding-agent@1.0.4"
|
||||
)
|
||||
|
||||
for bin in "${!PACKAGES[@]}"; do
|
||||
spec="${PACKAGES[$bin]}"
|
||||
name="$spec" want=""
|
||||
if [[ "${spec:1}" == *@* ]]; then name="${spec%@*}" want="${spec##*@}"; fi
|
||||
# Check the package, not the binary: a package that moved to a new name (Pi, from
|
||||
# @mariozechner) leaves the old one's binary behind, which would never be replaced.
|
||||
if [ ! -d "$PREFIX/lib/node_modules/${PACKAGES[$bin]}" ]; then
|
||||
echo "▸ Installing $bin (${PACKAGES[$bin]}) …"
|
||||
have=$(node -p "require('$PREFIX/lib/node_modules/$name/package.json').version" 2>/dev/null || true)
|
||||
if [ -z "$have" ] || { [ -n "$want" ] && [ "$have" != "$want" ]; }; then
|
||||
echo "▸ Installing $bin ($spec) …"
|
||||
rm -f "$PREFIX/bin/$bin"
|
||||
if ! npm install -g --prefix "$PREFIX" --no-fund --no-audit "${PACKAGES[$bin]}" >/dev/null 2>&1; then
|
||||
if ! npm install -g --prefix "$PREFIX" --no-fund --no-audit "$spec" >/dev/null 2>&1; then
|
||||
echo "⚠ Could not install $bin; plugin checks against it will report it missing." >&2
|
||||
continue
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
# 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
|
||||
- A non-loopback `--http` address with a token but no `--tls-cert`/`--tls-key` 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" <<YAML
|
||||
source: $CASE/skills
|
||||
targets:
|
||||
claude:
|
||||
skills:
|
||||
path: $CASE/claude-skills
|
||||
exclude: [notes]
|
||||
YAML
|
||||
for n in pdf notes off; do
|
||||
mkdir -p "$CASE/skills/$n"
|
||||
printf -- '---\nname: %s\ndescription: Use when testing %s\n---\n# %s\n' "$n" "$n" "$n" > "$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
|
||||
|
||||
### Step 8: A network listener without TLS is refused
|
||||
|
||||
```bash
|
||||
cd "$HOME"
|
||||
export SKILLSHARE_CONFIG="$HOME/mcp-serve/config.yaml"
|
||||
SKILLSHARE_MCP_TOKEN=change-me ss mcp serve -g --http 0.0.0.0:47943
|
||||
```
|
||||
|
||||
Expected:
|
||||
- exit_code: 1
|
||||
- --tls-cert
|
||||
|
||||
## Pass Criteria
|
||||
|
||||
- All steps marked PASS
|
||||
- No `ss mcp serve` process remains after Step 6
|
||||
@@ -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 --tls-cert --tls-key --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}")) ;;
|
||||
|
||||
@@ -52,6 +52,10 @@ 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 tls-cert -r -F -d 'serve --http: TLS certificate file'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command mcp' -l tls-key -r -F -d 'serve --http: TLS key file'
|
||||
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 +69,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'
|
||||
|
||||
@@ -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,10 @@ 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
|
||||
--tls-cert: string # serve --http: TLS certificate file
|
||||
--tls-key: string # serve --http: TLS key file
|
||||
--check # serve: list skipped skills without serving
|
||||
--no-tui
|
||||
--project(-p)
|
||||
--global(-g)
|
||||
|
||||
@@ -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', '--tls-cert', '--tls-key', '--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'
|
||||
|
||||
@@ -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,10 @@ _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:' \
|
||||
'--tls-cert[serve --http: TLS certificate file]:file:_files' \
|
||||
'--tls-key[serve --http: TLS key file]:file:_files' \
|
||||
'--check[serve: list skipped skills without serving]' \
|
||||
'--no-tui[Disable interactive menus]' \
|
||||
$global_flags \
|
||||
'--help[Show help]' \
|
||||
|
||||
@@ -420,11 +420,10 @@ func cmdDiffGlobal(targetName string, kind resourceKindFilter, opts diffRenderOp
|
||||
hasCopyMode := false
|
||||
for _, e := range entries {
|
||||
sc := e.target.SkillsConfig()
|
||||
filtered, err := sync.FilterSkills(discovered, sc.Include, sc.Exclude)
|
||||
filtered, err := sync.SelectTargetSkills(discovered, e.name, sc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("target %s has invalid include/exclude config: %w", e.name, err)
|
||||
}
|
||||
filtered = sync.FilterSkillsByTarget(filtered, e.name)
|
||||
fentries = append(fentries, filteredEntry{e, filtered})
|
||||
totalSkills += len(filtered)
|
||||
if e.mode == "copy" {
|
||||
|
||||
@@ -75,11 +75,10 @@ func cmdDiffProject(root, targetName string, kind resourceKindFilter, opts diffR
|
||||
if !sc.IsEnabled() {
|
||||
continue
|
||||
}
|
||||
filtered, err := sync.FilterSkills(discovered, sc.Include, sc.Exclude)
|
||||
filtered, err := sync.SelectTargetSkills(discovered, entry.Name, sc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("target %s has invalid include/exclude config: %w", entry.Name, err)
|
||||
}
|
||||
filtered = sync.FilterSkillsByTarget(filtered, entry.Name)
|
||||
mode := sc.Mode
|
||||
if mode == "" {
|
||||
mode = "merge"
|
||||
|
||||
@@ -744,13 +744,12 @@ func checkSyncDrift(cfg *config.Config, result *doctorResult, discovered []sync.
|
||||
continue
|
||||
}
|
||||
sc := target.SkillsConfig()
|
||||
filtered, err := sync.FilterSkills(discovered, sc.Include, sc.Exclude)
|
||||
filtered, err := sync.SelectTargetSkills(discovered, name, sc)
|
||||
if err != nil {
|
||||
ui.Row(ui.MarkFail, name, fmt.Sprintf("invalid include/exclude config: %v", err), width)
|
||||
result.addError()
|
||||
continue
|
||||
}
|
||||
filtered = sync.FilterSkillsByTarget(filtered, name)
|
||||
expectedCount := len(filtered)
|
||||
if expectedCount == 0 {
|
||||
continue
|
||||
|
||||
+12
-1
@@ -81,7 +81,14 @@ func main() {
|
||||
|
||||
// Migrate legacy dirs (backups/trash/logs) to XDG data/state dirs
|
||||
results = append(results, config.MigrateXDGDirs()...)
|
||||
// mcp serve speaks the protocol on stdout, so its errors, notices and trailers stay off it.
|
||||
serving := len(os.Args) > 2 && os.Args[1] == "mcp" && os.Args[2] == "serve"
|
||||
stdout := os.Stdout
|
||||
if serving {
|
||||
os.Stdout = os.Stderr // ui writes through fmt.Printf
|
||||
}
|
||||
reportMigrationResults(results)
|
||||
os.Stdout = stdout
|
||||
|
||||
// Set version for other packages to use
|
||||
versioncheck.Version = version
|
||||
@@ -131,6 +138,10 @@ func main() {
|
||||
if errors.As(err, &silent) {
|
||||
os.Exit(1)
|
||||
}
|
||||
if serving {
|
||||
fmt.Fprintf(os.Stderr, "✗ %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println()
|
||||
ui.Error("%v", err)
|
||||
os.Exit(1)
|
||||
@@ -140,7 +151,7 @@ func main() {
|
||||
// --format json/sarif/markdown) must produce only structured data on
|
||||
// stdout and nothing on stderr. Skip the trailing newline and update
|
||||
// check entirely so machine consumers get a clean payload.
|
||||
if !isStructuredOutput(args) {
|
||||
if !isStructuredOutput(args) && !serving {
|
||||
fmt.Println()
|
||||
|
||||
// Check for updates (non-blocking, silent on errors)
|
||||
|
||||
@@ -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 <addr> [--tls-cert <file> --tls-key <file>] [--target <name>];\nglobal unless -p; --check lists skipped skills without serving"},
|
||||
}},
|
||||
helpGroup{title: "Options", rows: []helpRow{
|
||||
{"--target <client>", "Receiving client; repeat for several, or none to keep the\nserver in Skillshare without writing it to any Agent"},
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"slices"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/skillserve"
|
||||
"skillshare/internal/ui"
|
||||
)
|
||||
|
||||
const mcpServeUsage = "skillshare mcp serve [--target <name>] [--http <addr> [--tls-cert <file> --tls-key <file>] | --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 {
|
||||
var target, addr, certFile, keyFile string
|
||||
valueFlags := map[string]*string{"--target": &target, "--http": &addr, "--tls-cert": &certFile, "--tls-key": &keyFile}
|
||||
mode, rest, err := parseModeArgs(args, slices.Collect(maps.Keys(valueFlags))...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
check := false
|
||||
for i := 0; i < len(rest); i++ {
|
||||
a := rest[i]
|
||||
if a == "--check" {
|
||||
check = true
|
||||
continue
|
||||
}
|
||||
v, ok := valueFlags[a]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown mcp serve argument %q; usage: %s", a, mcpServeUsage)
|
||||
}
|
||||
if i+1 == len(rest) {
|
||||
return fmt.Errorf("%s requires a value", a)
|
||||
}
|
||||
i++
|
||||
*v = rest[i]
|
||||
}
|
||||
if check && addr != "" {
|
||||
return fmt.Errorf("--check starts no server; drop --http")
|
||||
}
|
||||
if (certFile == "") != (keyFile == "") {
|
||||
return fmt.Errorf("--tls-cert and --tls-key go together")
|
||||
}
|
||||
if certFile != "" && addr == "" {
|
||||
return fmt.Errorf("--tls-cert and --tls-key need --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)
|
||||
}
|
||||
|
||||
// Off loopback, the token must exist and must not cross the network in plain text.
|
||||
token := os.Getenv(mcpServeTokenEnv)
|
||||
if addr != "" && !isLoopbackAddr(addr) {
|
||||
if token == "" {
|
||||
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)
|
||||
}
|
||||
if certFile == "" {
|
||||
return fmt.Errorf("refusing to send %s over plain HTTP on %s: pass --tls-cert and --tls-key, or bind a loopback address behind a TLS proxy", mcpServeTokenEnv, addr)
|
||||
}
|
||||
}
|
||||
|
||||
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 == "" {
|
||||
// A client stopping the server with a signal is a normal exit, as for --http.
|
||||
if err := srv.Run(ctx, &mcp.StdioTransport{}); !errors.Is(err, context.Canceled) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
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()
|
||||
}()
|
||||
if certFile == "" {
|
||||
fmt.Fprintf(os.Stderr, "Serving skills over MCP at http://%s/\n", ln.Addr())
|
||||
err = httpSrv.Serve(ln)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Serving skills over MCP at https://%s/\n", ln.Addr())
|
||||
err = httpSrv.ServeTLS(ln, certFile, keyFile)
|
||||
}
|
||||
if !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()
|
||||
}
|
||||
@@ -335,11 +335,11 @@ func printTargetsStatus(cfg *config.Config, discovered []sync.DiscoveredSkill) e
|
||||
// A target with skills off expects nothing, so it has no drift.
|
||||
expected := 0
|
||||
if sc.IsEnabled() && (mode == "merge" || mode == "copy") {
|
||||
filtered, err := sync.FilterSkills(discovered, sc.Include, sc.Exclude)
|
||||
filtered, err := sync.SelectTargetSkills(discovered, name, sc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("target %s has invalid include/exclude config: %w", name, err)
|
||||
}
|
||||
expected = len(sync.FilterSkillsByTarget(filtered, name))
|
||||
expected = len(filtered)
|
||||
notSynced = max(notSynced, expected-res.syncedCount)
|
||||
} else if sc.IsEnabled() && (len(sc.Include) > 0 || len(sc.Exclude) > 0) {
|
||||
warnings = append(warnings, name+": include/exclude ignored in symlink mode")
|
||||
|
||||
@@ -207,11 +207,11 @@ func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.Discov
|
||||
// A target with skills off expects nothing, so it has no drift.
|
||||
expected := 0
|
||||
if sc.IsEnabled() && (mode == "merge" || mode == "copy") {
|
||||
filtered, err := sync.FilterSkills(discovered, sc.Include, sc.Exclude)
|
||||
filtered, err := sync.SelectTargetSkills(discovered, entry.Name, sc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("target %s has invalid include/exclude config: %w", entry.Name, err)
|
||||
}
|
||||
expected = len(sync.FilterSkillsByTarget(filtered, entry.Name))
|
||||
expected = len(filtered)
|
||||
notSynced = max(notSynced, expected-res.syncedCount)
|
||||
} else if sc.IsEnabled() && (len(sc.Include) > 0 || len(sc.Exclude) > 0) {
|
||||
warnings = append(warnings, entry.Name+": include/exclude ignored in symlink mode")
|
||||
|
||||
@@ -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,13 +11,16 @@ 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
|
||||
golang.org/x/text v0.26.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
@@ -43,6 +45,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 +60,13 @@ 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/text v0.26.0 // indirect
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
)
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -98,11 +98,10 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc
|
||||
return dt
|
||||
}
|
||||
|
||||
filtered, err := ssync.FilterSkills(discovered, sc.Include, sc.Exclude)
|
||||
filtered, err := ssync.SelectTargetSkills(discovered, name, sc)
|
||||
if err != nil {
|
||||
return dt
|
||||
}
|
||||
filtered = ssync.FilterSkillsByTarget(filtered, name)
|
||||
resolution, err := ssync.ResolveTargetSkillsForTarget(name, config.ResourceTargetConfig{
|
||||
Path: sc.Path,
|
||||
TargetNaming: sc.TargetNaming,
|
||||
|
||||
@@ -139,12 +139,11 @@ func (s *Server) handleListTargets(w http.ResponseWriter, r *http.Request) {
|
||||
item.SkillsReadFrom = config.SkillsReadFrom(targets, name, projectRoot)
|
||||
case mode == "merge" || mode == "copy":
|
||||
if discoveredErr == nil {
|
||||
filtered, err := ssync.FilterSkills(discovered, sc.Include, sc.Exclude)
|
||||
filtered, err := ssync.SelectTargetSkills(discovered, name, sc)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid include/exclude for target "+name+": "+err.Error())
|
||||
return
|
||||
}
|
||||
filtered = ssync.FilterSkillsByTarget(filtered, name)
|
||||
resolution, resErr := ssync.ResolveTargetSkillsForTarget(name, config.ResourceTargetConfig{
|
||||
Path: sc.Path,
|
||||
TargetNaming: sc.TargetNaming,
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
// 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 (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
|
||||
"skillshare/internal/sourcewalk"
|
||||
"skillshare/internal/utils"
|
||||
)
|
||||
|
||||
// Per-skill limits from SEP-2640, and the Agent Skills field limits in characters.
|
||||
const (
|
||||
MaxFiles = 512
|
||||
MaxBytes = 16 << 20
|
||||
MaxDescription = 1024
|
||||
MaxCompatibility = 500
|
||||
)
|
||||
|
||||
// File is one regular file of a package. Digest and Size come from one read, so
|
||||
// they describe the same bytes even when the file changes while it is loaded.
|
||||
type File struct {
|
||||
Path string // absolute
|
||||
Rel string // slash-separated, relative to the package directory
|
||||
Digest string // sha256:<hex>
|
||||
Size int64
|
||||
}
|
||||
|
||||
// Package is a valid skill directory. Its SKILL.md entry is the read the
|
||||
// frontmatter was parsed from.
|
||||
type Package struct {
|
||||
Dir string // resolved
|
||||
Frontmatter map[string]any
|
||||
Files []File
|
||||
}
|
||||
|
||||
var errTooLarge = fmt.Errorf("is larger than %d MiB", MaxBytes>>20)
|
||||
|
||||
// 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)
|
||||
// A linked SKILL.md would be missing from the manifest, which lists no links.
|
||||
skillPath := filepath.Join(dir, "SKILL.md")
|
||||
info, err := os.Lstat(skillPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("SKILL.md is not a regular file")
|
||||
}
|
||||
content, err := readAtMost(skillPath, info, MaxBytes)
|
||||
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)
|
||||
}
|
||||
desc, _ := fm["description"].(string)
|
||||
if strings.TrimSpace(desc) == "" {
|
||||
return nil, fmt.Errorf("SKILL.md is missing a description")
|
||||
}
|
||||
if n := utf8.RuneCountInString(desc); n > MaxDescription {
|
||||
return nil, fmt.Errorf("description has %d characters; the limit is %d", n, MaxDescription)
|
||||
}
|
||||
// metadata is left unchecked: the format wants string values, but lists there are
|
||||
// common and tool clients read them fine, so skipping those skills would cost more.
|
||||
compat, ok := fm["compatibility"].(string)
|
||||
if _, set := fm["compatibility"]; set && (!ok || compat == "") {
|
||||
return nil, fmt.Errorf("compatibility must be non-empty text")
|
||||
}
|
||||
if n := utf8.RuneCountInString(compat); n > MaxCompatibility {
|
||||
return nil, fmt.Errorf("compatibility has %d characters; the limit is %d", n, MaxCompatibility)
|
||||
}
|
||||
|
||||
p := &Package{Dir: dir, Frontmatter: fm, Files: []File{{Path: skillPath, Rel: "SKILL.md", Digest: Digest(content), Size: int64(len(content))}}}
|
||||
// Every read is bounded by what is left of the package budget, so a file that
|
||||
// grows while it is read cannot push the package past the limit.
|
||||
left := MaxBytes - int64(len(content))
|
||||
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
|
||||
}
|
||||
rel, err := filepath.Rel(dir, path)
|
||||
if err != nil || rel == "SKILL.md" { // SKILL.md is listed from the read above
|
||||
return err
|
||||
}
|
||||
if len(p.Files) == MaxFiles {
|
||||
return fmt.Errorf("has more than %d files", MaxFiles)
|
||||
}
|
||||
sum, n, err := hashAtMost(path, info, left)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
left -= n
|
||||
p.Files = append(p.Files, File{Path: path, Rel: filepath.ToSlash(rel), Digest: sum, Size: n})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Digest is the manifest digest of b.
|
||||
func Digest(b []byte) string { return fmt.Sprintf("sha256:%x", sha256.Sum256(b)) }
|
||||
|
||||
// openSame opens path and checks that it is the file info (from Lstat) described,
|
||||
// so a file swapped for a link after it was checked is not followed.
|
||||
func openSame(path string, info os.FileInfo) (*os.File, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if got, err := f.Stat(); err != nil || !os.SameFile(info, got) {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("%s changed while it was read", filepath.Base(path))
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// readAtMost reads the file, failing past limit bytes.
|
||||
func readAtMost(path string, info os.FileInfo, limit int64) ([]byte, error) {
|
||||
f, err := openSame(path, info)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(f, limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, errTooLarge
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// hashAtMost streams the file into its digest and size, failing past limit bytes.
|
||||
func hashAtMost(path string, info os.FileInfo, limit int64) (string, int64, error) {
|
||||
f, err := openSame(path, info)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(h, io.LimitReader(f, limit+1))
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
if n > limit {
|
||||
return "", 0, errTooLarge
|
||||
}
|
||||
return fmt.Sprintf("sha256:%x", h.Sum(nil)), n, nil
|
||||
}
|
||||
|
||||
// ValidateName returns why a SKILL.md name breaks the Agent Skills naming rules
|
||||
// (including name == directory name), or "" when it follows them. Like the
|
||||
// reference validator, it checks lowercase Unicode letters and digits after NFKC
|
||||
// normalization and counts the limit in characters.
|
||||
func ValidateName(name, dirName string) string {
|
||||
// Not trimmed: surrounding whitespace is not a letter, digit or hyphen, so it fails below.
|
||||
exact := name
|
||||
name = norm.NFKC.String(name)
|
||||
if name == "" {
|
||||
return "SKILL.md is missing a name"
|
||||
}
|
||||
if utf8.RuneCountInString(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)
|
||||
}
|
||||
if name != strings.ToLower(name) || strings.ContainsFunc(name, func(r rune) bool {
|
||||
return r != '-' && !unicode.IsLetter(r) && !unicode.IsNumber(r)
|
||||
}) {
|
||||
return fmt.Sprintf("SKILL.md name %q must use only lowercase letters, numbers, and hyphens", name)
|
||||
}
|
||||
// Exactly, not only after NFKC: the directory is the skill path's last segment,
|
||||
// which the Skills extension requires to equal the name.
|
||||
if exact != dirName {
|
||||
return fmt.Sprintf("SKILL.md name %q does not match directory name %q", exact, dirName)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
// 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"
|
||||
"maps"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/skillpkg"
|
||||
"skillshare/internal/sourcewalk"
|
||||
ssync "skillshare/internal/sync"
|
||||
)
|
||||
|
||||
// extensionID is the SEP-2640 capability key.
|
||||
const extensionID = "io.modelcontextprotocol/skills"
|
||||
|
||||
var errNotFound = errors.New("not found")
|
||||
|
||||
// afterDiscover runs between discovery and the loads; tests change the tree there.
|
||||
var afterDiscover = func() {}
|
||||
|
||||
// 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, the
|
||||
// slash path inside it, and the digest it was listed with.
|
||||
type servedFile struct{ dir, rel, digest 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 URI; Skipped is in source path order.
|
||||
type Catalog struct {
|
||||
Skills []*Skill
|
||||
Skipped []Skip
|
||||
bySkill map[string]*Skill
|
||||
byFile map[string]servedFile
|
||||
}
|
||||
|
||||
// Builder builds catalogs from the skills source.
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
afterDiscover()
|
||||
// Discovery and the loads read the tree separately. A skill added, removed or
|
||||
// toggled in between would leave a parent publishing the files of a skill the
|
||||
// catalog does not list, so build again until discovery agrees with the loads.
|
||||
for range 3 {
|
||||
c, err := b.build(all)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
again, err := ssync.DiscoverSourceSkillsAll(b.Source, b.Walk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if slices.EqualFunc(all, again, func(x, y ssync.DiscoveredSkill) bool {
|
||||
return x.RelPath == y.RelPath && x.Disabled == y.Disabled
|
||||
}) {
|
||||
return c, nil
|
||||
}
|
||||
all = again
|
||||
}
|
||||
return nil, errors.New("the skills source kept changing while it was read; list the skills again")
|
||||
}
|
||||
|
||||
func (b *Builder) build(all []ssync.DiscoveredSkill) (*Catalog, error) {
|
||||
var err error
|
||||
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) })
|
||||
|
||||
// Deepest first, so a nested skill skipped for any reason also skips its parents,
|
||||
// which would otherwise publish its files as their own.
|
||||
c := &Catalog{bySkill: map[string]*Skill{}, byFile: map[string]servedFile{}}
|
||||
for i := len(selected) - 1; i >= 0; i-- {
|
||||
s := selected[i]
|
||||
skill, files, reason := load(s)
|
||||
if j := slices.IndexFunc(unserved, func(o string) bool { return strings.HasPrefix(o, s.RelPath+"/") }); reason == "" && j >= 0 {
|
||||
reason = fmt.Sprintf("contains %s, which is not served", unserved[j])
|
||||
}
|
||||
// A parent lists its nested skills' files under the same URIs. If one changed
|
||||
// between the two reads, the entries disagree; serve the parent next refresh
|
||||
// rather than overwrite what the nested skill advertises.
|
||||
for uri, f := range files {
|
||||
if old, ok := c.byFile[uri]; reason == "" && ok && old.digest != f.digest {
|
||||
reason = "a nested skill changed while it was read; it is served after the next refresh"
|
||||
}
|
||||
}
|
||||
if reason != "" {
|
||||
c.Skipped = append(c.Skipped, Skip{Path: s.RelPath, Reason: reason})
|
||||
unserved = append(unserved, s.RelPath)
|
||||
continue
|
||||
}
|
||||
c.Skills = append(c.Skills, skill)
|
||||
c.bySkill[skill.URI] = skill
|
||||
maps.Copy(c.byFile, files)
|
||||
}
|
||||
slices.Reverse(c.Skipped)
|
||||
// By URI, which skills/list cursors continue from.
|
||||
slices.SortFunc(c.Skills, func(x, y *Skill) int { return strings.Compare(x.URI, y.URI) })
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// load builds one entry and its files, or returns why the skill is skipped.
|
||||
// Every build reads every file again: size and mtime cannot prove the content is
|
||||
// unchanged (cp -p, rsync -t), and a stale digest makes hosts reject the file.
|
||||
func load(s ssync.DiscoveredSkill) (*Skill, map[string]servedFile, string) {
|
||||
p, err := skillpkg.Load(s.SourcePath)
|
||||
if err != nil {
|
||||
return nil, 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 {
|
||||
uri := base + "/" + escapePath(f.Rel)
|
||||
files[uri] = servedFile{dir: p.Dir, rel: f.Rel, digest: f.Digest}
|
||||
skill.Resources = append(skill.Resources, File{URI: uri, Digest: f.Digest, Size: f.Size})
|
||||
}
|
||||
return skill, files, ""
|
||||
}
|
||||
|
||||
// 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()
|
||||
data, err := io.ReadAll(io.LimitReader(f, skillpkg.MaxBytes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A file edited since it was listed would fail the client's digest check;
|
||||
// the next refresh lists it again.
|
||||
if skillpkg.Digest(data) != sf.digest {
|
||||
return nil, fmt.Errorf("%s changed since it was listed; list the skills again", uri)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package skillserve
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"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)
|
||||
}
|
||||
}
|
||||
|
||||
// A parent and its nested skill list the same files under the same URIs; an
|
||||
// unchanged tree serves both.
|
||||
func TestBuild_ServesParentAndNestedSkillTogether(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}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 2 {
|
||||
t.Errorf("skills=%v warnings=%v, want suite and suite/child served", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
// A nested skill created after discovery would otherwise be published only as a
|
||||
// file of its parent.
|
||||
func TestBuild_ListsNestedSkillCreatedDuringTheBuild(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "suite/SKILL.md"), skillMD("suite"))
|
||||
afterDiscover = func() { writeFile(t, filepath.Join(src, "suite/child/SKILL.md"), skillMD("child")) }
|
||||
t.Cleanup(func() { afterDiscover = func() {} })
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 2 {
|
||||
t.Errorf("skills=%v warnings=%v, want suite and suite/child served", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuild_SkipsParentOfInvalidNestedSkill(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("other"))
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 0 || !hasWarning(c, "contains suite/child") {
|
||||
t.Errorf("skills=%v warnings=%v, want suite skipped because its child is skipped", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
// A non-string key decodes to a map JSON cannot encode, which would fail the whole skills/list page.
|
||||
func TestBuild_SkipsSkillWhoseFrontmatterJSONCannotCarry(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "ok/SKILL.md"), skillMD("ok"))
|
||||
writeFile(t, filepath.Join(src, "odd/SKILL.md"), "---\nname: odd\ndescription: Use when testing odd\nmetadata:\n 1: x\n---\n")
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 1 || c.Skills[0].URI != "skill://ok/SKILL.md" || !hasWarning(c, "skipped odd") {
|
||||
t.Errorf("skills=%v warnings=%v, want odd skipped and ok served", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
// The Skills extension requires SKILL.md to begin with its frontmatter.
|
||||
func TestBuild_SkipsSkillWhoseFrontmatterIsNotAtTheStart(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "late/SKILL.md"), "# intro\n"+skillMD("late"))
|
||||
writeFile(t, filepath.Join(src, "open/SKILL.md"), "---\nname: open\ndescription: Use when testing open\n# open\n")
|
||||
writeFile(t, filepath.Join(src, "indented/SKILL.md"), " "+skillMD("indented"))
|
||||
writeFile(t, filepath.Join(src, "closer/SKILL.md"), "---\nname: closer\ndescription: Use when testing\n ---\n# closer\n")
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 0 || !hasWarning(c, "skipped late") || !hasWarning(c, "skipped open") || !hasWarning(c, "skipped indented") || !hasWarning(c, "skipped closer") {
|
||||
t.Errorf("skills=%v warnings=%v, want late, unclosed open and indented skipped", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
// The Agent Skills format caps a description at 1,024 characters and compatibility at 500, not bytes.
|
||||
func TestBuild_SkipsSkillWhoseDescriptionOrCompatibilityIsTooLong(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
skill := func(name, desc string) string { return "---\nname: " + name + "\ndescription: " + desc + "\n---\n" }
|
||||
writeFile(t, filepath.Join(src, "long/SKILL.md"), skill("long", strings.Repeat("a", 1025)))
|
||||
writeFile(t, filepath.Join(src, "wide/SKILL.md"), skill("wide", strings.Repeat("技", 1024)))
|
||||
writeFile(t, filepath.Join(src, "compat/SKILL.md"), "---\nname: compat\ndescription: Use when testing\ncompatibility: "+strings.Repeat("a", 501)+"\n---\n")
|
||||
writeFile(t, filepath.Join(src, "blank/SKILL.md"), "---\nname: blank\ndescription: Use when testing\ncompatibility: \"\"\n---\n")
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 1 || c.Skills[0].URI != "skill://wide/SKILL.md" || !hasWarning(c, "skipped long") || !hasWarning(c, "skipped compat") || !hasWarning(c, "skipped blank") {
|
||||
t.Errorf("skills=%v warnings=%v, want long and compat skipped, wide served", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
// The 16 MiB limit counts the bytes read, SKILL.md included.
|
||||
func TestBuild_SkipsSkillOverTheSizeLimit(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "big/SKILL.md"), skillMD("big"))
|
||||
writeFile(t, filepath.Join(src, "big/data.bin"), strings.Repeat("x", skillpkg.MaxBytes-len(skillMD("big"))+1))
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 0 || !hasWarning(c, "skipped big: is larger than 16 MiB") {
|
||||
t.Errorf("skills=%v warnings=%v, want big skipped", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
// The Agent Skills reference validator takes lowercase Unicode letters and digits,
|
||||
// after NFKC normalization, and counts the 64-character limit in characters.
|
||||
func TestBuild_AcceptsLowercaseUnicodeNames(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "技能-審查/SKILL.md"), skillMD("技能-審查"))
|
||||
writeFile(t, filepath.Join(src, "café/SKILL.md"), skillMD("café"))
|
||||
writeFile(t, filepath.Join(src, "Été/SKILL.md"), skillMD("Été"))
|
||||
writeFile(t, filepath.Join(src, "a_b/SKILL.md"), skillMD("a_b"))
|
||||
// The URI leaf is the directory, and it must equal the name exactly, not only after NFKC.
|
||||
writeFile(t, filepath.Join(src, "abc/SKILL.md"), skillMD("abc"))
|
||||
// Surrounding whitespace is not part of a valid name, even when the directory has it too.
|
||||
if runtime.GOOS != "windows" {
|
||||
writeFile(t, filepath.Join(src, " sp /SKILL.md"), strings.Replace(skillMD("x"), "name: x", `name: " sp "`, 1))
|
||||
}
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 2 || !hasWarning(c, "skipped Été") || !hasWarning(c, "skipped a_b") || !hasWarning(c, "skipped abc") || (runtime.GOOS != "windows" && !hasWarning(c, "skipped sp ")) {
|
||||
t.Errorf("skills=%v warnings=%v, want 技能-審查 and café served, Été, a_b and fullwidth abc skipped", 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)
|
||||
}
|
||||
// Same size and modification time, as cp -p or rsync -t leave it.
|
||||
info, err := os.Stat(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeFile(t, ref, "two")
|
||||
if err := os.Chtimes(ref, info.ModTime(), info.ModTime()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bytes that no longer match the listed digest would be rejected by a verifying client.
|
||||
func TestRead_RefusesFileChangedSinceListed(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "doc/SKILL.md"), skillMD("doc"))
|
||||
writeFile(t, filepath.Join(src, "doc/notes.md"), "one")
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeFile(t, filepath.Join(src, "doc/notes.md"), "two")
|
||||
|
||||
if _, err := c.Read("skill://doc/notes.md"); err == nil || !strings.Contains(err.Error(), "changed") {
|
||||
t.Errorf("Read error = %v, want the file reported as changed", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuild_ReadsFrontmatterAfterBOMOrWithCRLF(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "bom/SKILL.md"), "\ufeff"+skillMD("bom"))
|
||||
writeFile(t, filepath.Join(src, "crlf/SKILL.md"), strings.ReplaceAll(skillMD("crlf"), "\n", "\r\n"))
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 2 {
|
||||
t.Errorf("skills=%v warnings=%v, want bom and crlf served", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
// The walk lists no links, so a linked SKILL.md would leave the skill without its own file.
|
||||
func TestBuild_SkipsSkillWhoseSkillMDIsALink(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
target := filepath.Join(t.TempDir(), "SKILL.md")
|
||||
writeFile(t, target, skillMD("linked"))
|
||||
if err := os.MkdirAll(filepath.Join(src, "linked"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(target, filepath.Join(src, "linked/SKILL.md")); err != nil {
|
||||
t.Skip("symlinks unavailable:", err)
|
||||
}
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 0 || !hasWarning(c, "skipped linked") {
|
||||
t.Errorf("skills=%v warnings=%v, want linked skipped", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuild_SkipsSkillWithNonStringCompatibilityOrOversizedSkillMD(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "list/SKILL.md"), "---\nname: list\ndescription: Use when testing\ncompatibility: [linux]\n---\n")
|
||||
writeFile(t, filepath.Join(src, "huge/SKILL.md"), skillMD("huge")+strings.Repeat("x", skillpkg.MaxBytes))
|
||||
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Skills) != 0 || !hasWarning(c, "skipped list") || !hasWarning(c, "skipped huge: is larger than 16 MiB") {
|
||||
t.Errorf("skills=%v warnings=%v, want list and huge skipped", c.Skills, c.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRead_ServesListedFileWithBackslashInName(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a backslash separates paths on Windows")
|
||||
}
|
||||
src := t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "doc/SKILL.md"), skillMD("doc"))
|
||||
writeFile(t, filepath.Join(src, `doc/a\b.txt`), "x")
|
||||
c, err := (&Builder{Source: src}).Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data, err := c.Read("skill://doc/a%5Cb.txt"); err != nil || string(data) != "x" {
|
||||
t.Errorf("Read = %q, %v; want the listed file", data, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package skillserve
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"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. Cross-origin browser requests are
|
||||
// refused, so a web page cannot reach a loopback server that has no token.
|
||||
func HTTPHandler(srv *mcp.Server, token string) http.Handler {
|
||||
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, &mcp.StreamableHTTPOptions{
|
||||
Stateless: true,
|
||||
CrossOriginProtection: http.NewCrossOriginProtection(),
|
||||
})
|
||||
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
|
||||
}
|
||||
// The cursor is the last URI returned, not an offset: the catalog may be rebuilt
|
||||
// between pages, and skills added or removed before it must not shift the next page.
|
||||
start := 0
|
||||
if p != nil && p.Cursor != "" {
|
||||
if !strings.HasPrefix(p.Cursor, "skill://") {
|
||||
return nil, invalidParams("invalid cursor")
|
||||
}
|
||||
start = sort.Search(len(c.Skills), func(i int) bool { return c.Skills[i].URI > p.Cursor })
|
||||
}
|
||||
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 = c.Skills[end-1].URI
|
||||
}
|
||||
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"
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// The catalog may be rebuilt between pages; a skill added ahead of the cursor
|
||||
// must not shift the next page onto entries already returned.
|
||||
func TestServer_ListContinuesAfterTheLastSkillReturned(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) // Refresh 0: every call rebuilds
|
||||
|
||||
first := listSkills(t, cs, "")
|
||||
writeFile(t, filepath.Join(src, "a000", "SKILL.md"), skillMD("a000"))
|
||||
second := listSkills(t, cs, first.NextCursor)
|
||||
if len(second.Skills) != 1 || second.Skills[0].URI != "skill://s100/SKILL.md" {
|
||||
t.Errorf("second page = %v, want only skill://s100/SKILL.md", second.Skills)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A web page in the browser must not reach a loopback server that has no token.
|
||||
func TestHTTPHandler_RejectsCrossOriginBrowserRequests(t *testing.T) {
|
||||
srv, err := NewServer(&Builder{Source: t.TempDir()}, Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8765/", strings.NewReader(`{}`))
|
||||
req.Header.Set("Origin", "https://evil.example")
|
||||
req.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||
rec := httptest.NewRecorder()
|
||||
HTTPHandler(srv, "").ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("cross-origin request: status %d, want 403", 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))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package sync
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/config"
|
||||
@@ -33,12 +32,10 @@ func TargetSkills(name string, target config.TargetConfig, defaultMode, sourcePa
|
||||
return discovered, nil
|
||||
}
|
||||
|
||||
enabled := slices.DeleteFunc(slices.Clone(discovered), func(s DiscoveredSkill) bool { return s.Disabled })
|
||||
skills, err := FilterSkills(enabled, sc.Include, sc.Exclude)
|
||||
skills, err := SelectTargetSkills(discovered, name, sc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
skills = FilterSkillsByTarget(skills, name)
|
||||
return append(skills, localTargetSkills(sc.Path, sourcePath)...), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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)))
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package utils
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -211,6 +213,48 @@ func extractFrontmatterRaw(filePath string) string {
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// ParseFrontmatterMap returns the complete YAML frontmatter of SKILL.md content.
|
||||
// The Agent Skills format requires the file to begin with it, closed by a second ---.
|
||||
func ParseFrontmatterMap(content []byte) (map[string]any, error) {
|
||||
content = bytes.TrimPrefix(content, []byte("\xef\xbb\xbf"))
|
||||
// Scan line by line up to the closing ---, keeping only offsets, so memory does
|
||||
// not grow with the line count of a large body.
|
||||
start, end := -1, -1
|
||||
pos := 0
|
||||
for line := range bytes.Lines(content) {
|
||||
if start < 0 {
|
||||
// Exactly ---: an indented delimiter does not open frontmatter. CRLF is fine.
|
||||
if string(bytes.TrimRight(line, "\r\n")) != "---" {
|
||||
return nil, fmt.Errorf("no frontmatter at the start")
|
||||
}
|
||||
start = len(line)
|
||||
} else if string(bytes.TrimRight(line, "\r\n")) == "---" { // also exactly ---
|
||||
end = pos
|
||||
break
|
||||
}
|
||||
pos += len(line)
|
||||
}
|
||||
if start < 0 {
|
||||
return nil, fmt.Errorf("no frontmatter at the start")
|
||||
}
|
||||
if end < 0 {
|
||||
return nil, fmt.Errorf("unclosed frontmatter: no closing ---")
|
||||
}
|
||||
raw := string(content[start:end])
|
||||
if strings.TrimSpace(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)
|
||||
}
|
||||
// A non-string key decodes to map[any]any, which JSON cannot carry.
|
||||
if _, err := json.Marshal(fm); err != nil {
|
||||
return nil, fmt.Errorf("frontmatter JSON cannot carry: %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).
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -307,3 +309,18 @@ enabled: true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A newline-heavy body must not cost memory per line: only the frontmatter is kept.
|
||||
func TestParseFrontmatterMap_MemoryDoesNotGrowWithBodyLines(t *testing.T) {
|
||||
content := append([]byte("---\nname: a\n---\n"), bytes.Repeat([]byte("\n"), 16<<20)...)
|
||||
var before, after runtime.MemStats
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&before)
|
||||
if _, err := ParseFrontmatterMap(content); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime.ReadMemStats(&after)
|
||||
if got := after.TotalAlloc - before.TotalAlloc; got > 1<<20 {
|
||||
t.Errorf("parsing allocated %d bytes, want under 1 MiB", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,8 +33,8 @@ Check `skillshare <command> --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
|
||||
|
||||
@@ -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 [--tls-cert F --tls-key F]] # 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,18 @@ 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, description missing or over 1,024
|
||||
characters, compatibility over 500, over 512 files/16 MiB) are
|
||||
listed on stderr; `--check` lists them without serving. `--http` on a non-loopback address requires `SKILLSHARE_MCP_TOKEN` and `--tls-cert`/`--tls-key` (or bind loopback behind a TLS proxy).
|
||||
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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//go:build !online
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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")
|
||||
}
|
||||
|
||||
// A token sent over plain HTTP off loopback can be read by anyone on the path.
|
||||
func TestMCPServe_RefusesPlainHTTPNetworkListener(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
r := sb.RunCLIEnv(map[string]string{"SKILLSHARE_MCP_TOKEN": "secret"}, "mcp", "serve", "--http", "0.0.0.0:0")
|
||||
|
||||
r.AssertFailure(t)
|
||||
r.AssertAnyOutputContains(t, "--tls-cert")
|
||||
}
|
||||
|
||||
func TestMCPServe_RequiresBothTLSFiles(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
r := sb.RunCLI("mcp", "serve", "--http", "127.0.0.1:0", "--tls-cert", "cert.pem")
|
||||
|
||||
r.AssertFailure(t)
|
||||
r.AssertAnyOutputContains(t, "--tls-cert and --tls-key go together")
|
||||
}
|
||||
|
||||
func TestMCPServe_ServesHTTPSOffLoopbackWithTokenAndCertificate(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n")
|
||||
certFile, keyFile := writeSelfSignedCert(t)
|
||||
|
||||
cmd := exec.Command(sb.BinaryPath, "mcp", "serve", "--http", "0.0.0.0:0", "--tls-cert", certFile, "--tls-key", keyFile)
|
||||
cmd.Env = append(os.Environ(), "HOME="+sb.Home, "SKILLSHARE_CONFIG="+sb.ConfigPath, "SKILLSHARE_MCP_TOKEN=secret")
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }()
|
||||
line, _ := bufio.NewReader(stderr).ReadString('\n')
|
||||
if !strings.Contains(line, "https://") {
|
||||
t.Errorf("first stderr line = %q, want the https:// address", line)
|
||||
}
|
||||
}
|
||||
|
||||
func writeSelfSignedCert(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test"}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour)}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyDER, err := x509.MarshalECPrivateKey(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
certFile, keyFile := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
|
||||
if err := os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return certFile, keyFile
|
||||
}
|
||||
|
||||
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")
|
||||
|
||||
// stdout is the protocol stream, so the error goes to stderr alone.
|
||||
r.AssertFailure(t)
|
||||
r.AssertErrorContains(t, `unknown target "nope"`)
|
||||
if r.Stdout != "" {
|
||||
t.Errorf("stdout = %q, want nothing", r.Stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPServe_ReportsLegacyMigrationOnStderr(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n")
|
||||
// A legacy trash folder in the config dir is moved to the data dir by the first command.
|
||||
if err := os.MkdirAll(filepath.Join(sb.Home, ".config", "skillshare", "trash"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(filepath.Join(sb.Home, ".local", "share", "skillshare", "trash")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := sb.RunCLI("mcp", "serve", "--target", "nope")
|
||||
|
||||
r.AssertErrorContains(t, "Moved legacy data")
|
||||
if r.Stdout != "" {
|
||||
t.Errorf("stdout = %q, want nothing", r.Stdout)
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { useAppContext } from '../../context/AppContext';
|
||||
import { shortenHome } from '../../lib/paths';
|
||||
import { describeEndpoint, describeError, hasToolPolicy, targetLabel, parsePiOptions } from './mcpView';
|
||||
import { MCPTargetOrder } from './targetOrder';
|
||||
import type { AddMode } from './mcpServerDraft';
|
||||
|
||||
/** Where the configuration comes from. Each entry point fixes one; the dialog never switches. */
|
||||
type Source = 'target' | 'paste';
|
||||
@@ -57,7 +58,7 @@ interface Props {
|
||||
/** Overrides the targets offered, for a project where only some Agents have a file. */
|
||||
availableTargets?: readonly string[];
|
||||
/** Present when this is the paste half of "add a server", so the user can swap back to the form. */
|
||||
onMode?: (mode: 'form' | 'paste') => void;
|
||||
onMode?: (mode: AddMode) => void;
|
||||
onClose: () => void;
|
||||
onImported: () => void;
|
||||
}
|
||||
@@ -390,11 +391,11 @@ export default function MCPImportDialog(props: Props) {
|
||||
</div>
|
||||
<div className="db">
|
||||
{onMode && (
|
||||
<SegmentedControl<'form' | 'paste'>
|
||||
<SegmentedControl<AddMode>
|
||||
className="self-start"
|
||||
value="paste"
|
||||
onChange={onMode}
|
||||
options={[{ value: 'form', label: t('mcp.manualTab') }, { value: 'paste', label: t('mcp.pasteTab') }]}
|
||||
options={[{ value: 'form', label: t('mcp.manualTab') }, { value: 'paste', label: t('mcp.pasteTab') }, { value: 'serve', label: 'Skillshare' }]}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import MCPCheckNote from './MCPCheckNote';
|
||||
import MCPImportDialog from './MCPImportDialog';
|
||||
import MCPRemoveDialog from './MCPRemoveDialog';
|
||||
import MCPServerDialog from './MCPServerDialog';
|
||||
import { isServeCommand, type AddMode } from './mcpServerDraft';
|
||||
import MCPServerList from './MCPServerList';
|
||||
import MCPSyncBox, { MCPRailActions } from './MCPSyncBox';
|
||||
import MCPUnmanagedNote from './MCPUnmanagedNote';
|
||||
@@ -71,8 +72,10 @@ function ProjectSettings({ model, offered, pickTargets, onPickTargets, busy, sav
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectServerEditor({ data, model, root, offered, editing, addingOff, addMode, onMode, onClose, onSaved }: { data: MCPList; model: ProjectModel; root: string; offered: readonly string[]; editing: string; addingOff: boolean; addMode: 'form' | 'paste'; onMode: (mode: 'form' | 'paste') => void; onClose: () => void; onSaved: () => void }) {
|
||||
function ProjectServerEditor({ data, model, root, offered, editing, addingOff, addMode, onMode, onClose, onSaved }: { data: MCPList; model: ProjectModel; root: string; offered: readonly string[]; editing: string; addingOff: boolean; addMode: AddMode; onMode: (mode: AddMode) => void; onClose: () => void; onSaved: () => void }) {
|
||||
const { servers, targets, own } = model;
|
||||
const server = editing ? own[editing] : undefined;
|
||||
const serve = editing === '' ? addMode === 'serve' : isServeCommand(server);
|
||||
return (
|
||||
editing === '' && addMode === 'paste' ? (
|
||||
<MCPImportDialog
|
||||
@@ -89,9 +92,11 @@ function ProjectServerEditor({ data, model, root, offered, editing, addingOff, a
|
||||
/>
|
||||
) : (
|
||||
<MCPServerDialog
|
||||
key={addMode}
|
||||
project={root}
|
||||
off={editing === '' && addingOff}
|
||||
initial={editing ? { name: editing, server: own[editing] } : undefined}
|
||||
serve={serve}
|
||||
initial={editing && server ? { name: editing, server } : undefined}
|
||||
defaultTargets={targets}
|
||||
existingNames={Object.keys(servers)}
|
||||
availableTargets={offered}
|
||||
@@ -109,7 +114,7 @@ export default function MCPProjectView({ data, root, offered, onChanged, onRemov
|
||||
const { toast } = useToast();
|
||||
const [pickTargets, setPickTargets] = useState(false);
|
||||
const [editing, setEditing] = useState<string | null>(null); // '' adds a new server
|
||||
const [addMode, setAddMode] = useState<'form' | 'paste'>('form');
|
||||
const [addMode, setAddMode] = useState<AddMode>('form');
|
||||
const [addingOff, setAddingOff] = useState(false); // the new entry is a switch, not a server
|
||||
const [removing, setRemoving] = useState('');
|
||||
const [dropping, setDropping] = useState(false);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { api, type Target } from '../../api/client';
|
||||
import { mcpApi } from '../../api/mcp';
|
||||
import { mcpCheckApi } from '../../api/mcpCheck';
|
||||
import { I18nProvider } from '../../i18n';
|
||||
@@ -55,6 +56,8 @@ describe('MCP server dialog', () => {
|
||||
});
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks(); localStorage.clear();
|
||||
vi.spyOn(api, 'listTargets').mockResolvedValue({ targets: [], sourceSkillCount: 0 });
|
||||
vi.spyOn(api, 'availableTargets').mockResolvedValue({ targets: [] });
|
||||
HTMLElement.prototype.scrollIntoView = vi.fn();
|
||||
vi.mocked(mcpApi.save).mockResolvedValue({ applied: [], backupIds: [] });
|
||||
});
|
||||
@@ -77,6 +80,50 @@ describe('MCP server dialog', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('serves every enabled skill from the Skillshare tab, with no command to type', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog({ serve: true });
|
||||
expect(screen.queryByLabelText('Command')).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(mcpApi.save).toHaveBeenCalledWith({ name: 'skillshare', server: { command: 'skillshare', args: ['mcp', 'serve'] }, replace: false }));
|
||||
});
|
||||
|
||||
// A root under mcp.projects is served from the global config, where its targets live, so no -p.
|
||||
it("serves a project's own target selection from the global config", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(api.listTargets).mockResolvedValue({
|
||||
targets: [
|
||||
{ name: 'claude', skillsEnabled: true },
|
||||
{ name: 'app@claude', project: '/work/app', skillsEnabled: true },
|
||||
{ name: 'web@claude', project: '/work/web', skillsEnabled: true },
|
||||
] as Target[],
|
||||
sourceSkillCount: 1,
|
||||
});
|
||||
renderDialog({ serve: true, project: '/work/app' });
|
||||
await user.click(screen.getByRole('combobox', { name: 'Skills to serve' }));
|
||||
const own = await screen.findByRole('option', { name: 'Same as target app@claude' });
|
||||
expect(screen.queryByRole('option', { name: 'Same as target web@claude' })).not.toBeInTheDocument();
|
||||
await user.click(own);
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(mcpApi.save).toHaveBeenCalledWith(expect.objectContaining({ server: { command: 'skillshare', args: ['mcp', 'serve', '--target', 'app@claude'] } })));
|
||||
});
|
||||
|
||||
it("keeps an existing command's -p when the served target changes", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(api.listTargets).mockResolvedValue({ targets: [{ name: 'old', skillsEnabled: true }, { name: 'new', skillsEnabled: true }] as Target[], sourceSkillCount: 1 });
|
||||
renderDialog({ serve: true, initial: { name: 'skillshare', server: { command: 'skillshare', args: ['mcp', 'serve', '-p', '--target', 'old'] } } });
|
||||
await user.click(screen.getByRole('combobox', { name: 'Skills to serve' }));
|
||||
await user.click(await screen.findByRole('option', { name: 'Same as target new' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(mcpApi.save).toHaveBeenCalledWith(expect.objectContaining({ server: expect.objectContaining({ command: 'skillshare', args: ['mcp', 'serve', '--target', 'new', '-p'] }) })));
|
||||
});
|
||||
|
||||
it('warns that an Agent already getting skills by sync would see them twice', async () => {
|
||||
vi.mocked(api.listTargets).mockResolvedValue({ targets: [{ name: 'claude', skillsEnabled: true } as Target], sourceSkillCount: 1 });
|
||||
renderDialog({ serve: true });
|
||||
expect(await screen.findByText(/already get these skills by sync/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('pins targets when the selection differs from the inherited default', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useContext, useState } from 'react';
|
||||
import { Check, KeyRound, Link2, Plus, SquareTerminal, X } from 'lucide-react';
|
||||
import { mcpApi, mcpOffTargets, type MCPMutation, type MCPServer } from '../../api/mcp';
|
||||
import { useAvailableTargetsQuery, useSyncedTargetsQuery } from '../../hooks/useSharedQueries';
|
||||
import { shortenHome } from '../../lib/paths';
|
||||
import AgentIcon from '../AgentIcon';
|
||||
import Button from '../Button';
|
||||
import DialogShell from '../DialogShell';
|
||||
@@ -13,7 +15,20 @@ import ToolPolicyFields from './ToolPolicyFields';
|
||||
import MCPConfigView from './MCPConfigView';
|
||||
import { cleanToolPolicy, describeError, hasToolPolicy, targetLabel } from './mcpView';
|
||||
import { MCPTargetOrder } from './targetOrder';
|
||||
import { initialServerDraft, validateServerDraft, type DraftPatch, type EnvRow, type ServerDraft, type ServerValidation } from './mcpServerDraft';
|
||||
import { initialServerDraft, serveSkillsCommand, serveSkillsTarget, validateServerDraft, type AddMode, type DraftPatch, type EnvRow, type ServerDraft, type ServerValidation } from './mcpServerDraft';
|
||||
|
||||
/**
|
||||
* For the Skillshare tab: the skills targets that can be served, and the Agents that already get skills by sync.
|
||||
* A root under mcp.projects adds its own project targets (app@claude), which live in the global config too.
|
||||
*/
|
||||
function useSkillTargets(enabled: boolean, project?: string) {
|
||||
const own = useSyncedTargetsQuery({ enabled });
|
||||
const tools = useAvailableTargetsQuery({ enabled });
|
||||
const on = (own.data?.targets ?? []).filter((x) => x.skillsEnabled && (!x.project || (project !== undefined && shortenHome(x.project) === shortenHome(project))));
|
||||
// A target syncs skills to its Agent, named after the @ in a project target; a tool also reads other targets' folders (universal's ~/.agents/skills).
|
||||
const synced = new Set([...on.map((x) => x.agent ?? x.name.slice(x.name.lastIndexOf('@') + 1)), ...(tools.data?.targets ?? []).filter((x) => x.readsFrom?.length).map((x) => x.name)]);
|
||||
return { names: on.map((x) => x.name), synced };
|
||||
}
|
||||
|
||||
const valueMap = (rows: EnvRow[]) => Object.fromEntries(rows.filter((r) => r.key.trim()).map((r) => [r.key.trim(), r.fromEnv ? { fromEnv: r.value.trim() } : r.value]));
|
||||
|
||||
@@ -68,7 +83,9 @@ interface Props {
|
||||
/** Adds a switch that turns off a server the Agent defines globally, not a server. */
|
||||
off?: boolean;
|
||||
/** Present when adding, so the user can swap to pasting a snippet instead of filling the fields. */
|
||||
onMode?: (mode: 'form' | 'paste') => void;
|
||||
onMode?: (mode: AddMode) => void;
|
||||
/** The server is `skillshare mcp serve`: ask what to serve instead of a command. */
|
||||
serve?: boolean;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}
|
||||
@@ -83,6 +100,8 @@ interface ServerFormProps {
|
||||
order: readonly string[];
|
||||
visibleTargets: Set<string>;
|
||||
isProject: boolean;
|
||||
project?: string;
|
||||
serve: boolean;
|
||||
onMode: Props['onMode'];
|
||||
onSave: () => Promise<void>;
|
||||
error: string;
|
||||
@@ -92,23 +111,28 @@ interface ServerFormProps {
|
||||
mutation?: MCPMutation;
|
||||
}
|
||||
|
||||
function ServerForm({ draft, validation, patch, off, saving, editing, order, visibleTargets, isProject, onMode, onSave, error, probe, mutation }: ServerFormProps) {
|
||||
function ServerForm({ draft, validation, patch, off, saving, editing, order, visibleTargets, isProject, project, serve, onMode, onSave, error, probe, mutation }: ServerFormProps) {
|
||||
const t = useT();
|
||||
const { isProjectMode } = useAppContext();
|
||||
const { name, http, targets } = draft;
|
||||
const { nameError } = validation;
|
||||
const selectedTargets = new Set(targets);
|
||||
const skillTargets = useSkillTargets(serve, project);
|
||||
const served = serveSkillsTarget(validation.words) ?? '';
|
||||
const twice = serve ? order.filter((x) => selectedTargets.has(x) && skillTargets.synced.has(x)) : [];
|
||||
return (
|
||||
<form id="mcp-server" className="db" onSubmit={(e) => { e.preventDefault(); void onSave(); }}>
|
||||
{/* Pasting a snippet only makes sense for a server, not for an off switch. */}
|
||||
{onMode && !off && (
|
||||
<SegmentedControl<'form' | 'paste'>
|
||||
<SegmentedControl<AddMode>
|
||||
className="self-start"
|
||||
value="form"
|
||||
value={serve ? 'serve' : 'form'}
|
||||
onChange={onMode}
|
||||
options={[{ value: 'form', label: t('mcp.manualTab') }, { value: 'paste', label: t('mcp.pasteTab') }]}
|
||||
options={[{ value: 'form', label: t('mcp.manualTab') }, { value: 'paste', label: t('mcp.pasteTab') }, { value: 'serve', label: 'Skillshare' }]}
|
||||
/>
|
||||
)}
|
||||
{off && <div className="ss-note inf"><span className="flex-1">{t('mcp.offHint')}</span></div>}
|
||||
{serve && <p className="m-0 text-[13px] text-ink-2">{t('mcp.serve.intro')}</p>}
|
||||
<div className="grid grid-cols-2 gap-3.5">
|
||||
<div className="ss-fld">
|
||||
<label htmlFor="mcp-name">{off ? t('mcp.offName') : t('mcp.name')}</label>
|
||||
@@ -117,7 +141,17 @@ function ServerForm({ draft, validation, patch, off, saving, editing, order, vis
|
||||
</span>
|
||||
{nameError && <span className="hp !text-bad">{nameError}</span>}
|
||||
</div>
|
||||
{!off && (
|
||||
{serve && (
|
||||
<Select
|
||||
label={t('mcp.serve.which')}
|
||||
value={served}
|
||||
// An edited command keeps its own -p; the dashboard scope only decides for a new one.
|
||||
onChange={(v) => patch({ command: serveSkillsCommand(v, isProjectMode || validation.words.some((w) => w === '-p' || w === '--project')) })}
|
||||
options={[{ value: '', label: t('mcp.serve.all') }, ...[...new Set([...skillTargets.names, ...(served ? [served] : [])])].map((x) => ({ value: x, label: t('mcp.serve.like', { name: x }) }))]}
|
||||
disabled={saving}
|
||||
/>
|
||||
)}
|
||||
{!off && !serve && (
|
||||
<div className="ss-fld">
|
||||
<span className="text-[13px] font-semibold">{t('mcp.transport')}</span>
|
||||
<SegmentedControl
|
||||
@@ -130,7 +164,17 @@ function ServerForm({ draft, validation, patch, off, saving, editing, order, vis
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!off && <ConnectionFields draft={draft} patch={patch} saving={saving} />}
|
||||
{!off && !serve && <ConnectionFields draft={draft} patch={patch} saving={saving} />}
|
||||
{serve && (
|
||||
<div className="ss-fld">
|
||||
<span className="text-[13px] font-semibold">{t('mcp.serve.runs')}</span>
|
||||
<span className="ss-inp font-mono !bg-sunken">
|
||||
<SquareTerminal size={15} className="shrink-0 text-ink-3" />
|
||||
<code>{draft.command}</code>
|
||||
</span>
|
||||
<span className="hp">{t('mcp.serve.runsHint')}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="ss-fld">
|
||||
<span className="text-[13px] font-semibold">{off ? t('mcp.offTargets') : t('mcp.targets')}</span>
|
||||
@@ -149,14 +193,16 @@ function ServerForm({ draft, validation, patch, off, saving, editing, order, vis
|
||||
>
|
||||
<span className="ic"><AgentIcon target={target} size={20} /><i><Check size={9} strokeWidth={3.5} /></i></span>
|
||||
{targetLabel(target)}{target === 'claude-desktop' && <span className="ss-tag">stdio</span>}
|
||||
{serve && skillTargets.synced.has(target) && <span className="ss-tag">{t('mcp.serve.synced')}</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{/* A switch-only entry only turns a server off, so it has no tools to choose. */}
|
||||
{!off && <ToolPolicyFields tools={draft.tools} onChange={(tools) => patch({ tools })} error={validation.toolsError} disabled={saving} probe={probe} mutation={mutation} />}
|
||||
{targets.includes('pi') && !off && <PiSettingsFields optionsText={draft.piOptions} options={validation.options} optionsError={validation.optionsError} onOptions={(piOptions) => patch({ piOptions })} disabled={saving} project={isProject} toolsSet={hasToolPolicy(draft.tools)} />}
|
||||
{twice.length > 0 && <div className="ss-note warn"><span className="flex-1">{t('mcp.serve.twice', { names: twice.map(targetLabel).join(', ') })}</span></div>}
|
||||
{/* A switch-only entry only turns a server off, so it has no tools to choose; skillshare mcp serve offers none. */}
|
||||
{!off && !serve && <ToolPolicyFields tools={draft.tools} onChange={(tools) => patch({ tools })} error={validation.toolsError} disabled={saving} probe={probe} mutation={mutation} />}
|
||||
{targets.includes('pi') && !off && !serve && <PiSettingsFields optionsText={draft.piOptions} options={validation.options} optionsError={validation.optionsError} onOptions={(piOptions) => patch({ piOptions })} disabled={saving} project={isProject} toolsSet={hasToolPolicy(draft.tools)} />}
|
||||
{error && <div className="ss-note bad"><span className="flex-1">{error}</span></div>}
|
||||
</form>
|
||||
);
|
||||
@@ -219,7 +265,7 @@ function ServerFooter({ targets, off, complete, canSave, saving, onView, onClose
|
||||
}
|
||||
|
||||
/** Add or edit one source server. Saving only changes the source; Sync writes the config files. */
|
||||
export default function MCPServerDialog({ initial, defaultTargets, existingNames, availableTargets: offered, project, off: offKind = false, onMode, onClose, onSaved }: Props) {
|
||||
export default function MCPServerDialog({ initial, defaultTargets, existingNames, availableTargets: offered, project, off: offKind = false, onMode, serve = false, onClose, onSaved }: Props) {
|
||||
const t = useT();
|
||||
const { isProjectMode } = useAppContext();
|
||||
const order = useContext(MCPTargetOrder);
|
||||
@@ -228,7 +274,12 @@ export default function MCPServerDialog({ initial, defaultTargets, existingNames
|
||||
// The entry point already chose which kind of entry this is, so the dialog never asks again.
|
||||
const off = initial ? Boolean(server?.disabled) : offKind;
|
||||
const offTargets = mcpOffTargets;
|
||||
const [draft, setDraft] = useState(() => initialServerDraft(server, initial?.name ?? '', defaultTargets, off));
|
||||
const isProject = Boolean(project) || isProjectMode;
|
||||
const [draft, setDraft] = useState(() => {
|
||||
const start = initialServerDraft(server, initial?.name ?? '', defaultTargets, off);
|
||||
// Only a project-mode dashboard serves with -p; a root under mcp.projects is served from the global config.
|
||||
return serve && !server ? { ...start, name: 'skillshare', command: serveSkillsCommand('', isProjectMode) } : start;
|
||||
});
|
||||
const patch: DraftPatch = (change) => setDraft((prev) => ({ ...prev, ...change }));
|
||||
const { http, url, tokenEnv, headers, env, targets } = draft;
|
||||
const [viewing, setViewing] = useState(false);
|
||||
@@ -295,7 +346,7 @@ export default function MCPServerDialog({ initial, defaultTargets, existingNames
|
||||
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose} disabled={saving}><X size={16} /></button>
|
||||
</div>
|
||||
{/* The view takes the whole body, so a long file has room; the fields live in state and come back as they were. */}
|
||||
{viewing ? <div className="db"><MCPConfigView mutation={mutation} /></div> : <ServerForm draft={draft} validation={validation} patch={patch} off={off} saving={saving} editing={Boolean(initial)} order={order} visibleTargets={visibleTargets} isProject={Boolean(project) || isProjectMode} onMode={onMode} onSave={save} error={error} probe={probe} mutation={complete ? mutation : undefined} />}
|
||||
{viewing ? <div className="db"><MCPConfigView mutation={mutation} /></div> : <ServerForm draft={draft} validation={validation} patch={patch} off={off} saving={saving} editing={Boolean(initial)} order={order} visibleTargets={visibleTargets} isProject={isProject} project={project} serve={serve} onMode={onMode} onSave={save} error={error} probe={probe} mutation={complete ? mutation : undefined} />}
|
||||
{viewing ? <div className="df"><Button variant="secondary" onClick={() => setViewing(false)}>{t('common.back')}</Button></div> : <ServerFooter targets={targets} off={off} complete={complete} canSave={canSave} saving={saving} onView={() => setViewing(true)} onClose={onClose} />}
|
||||
</DialogShell>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { initialServerDraft } from './mcpServerDraft';
|
||||
import { initialServerDraft, serveSkillsCommand, serveSkillsTarget } from './mcpServerDraft';
|
||||
import { splitCommand } from './mcpView';
|
||||
|
||||
describe('MCP server drafts', () => {
|
||||
it('starts from the Pi settings of a server being edited', () => {
|
||||
@@ -13,4 +14,13 @@ describe('MCP server drafts', () => {
|
||||
it('keeps only Agents with a switch in the targets a new off switch starts with', () => {
|
||||
expect(initialServerDraft(undefined, '', ['claude', 'cursor', 'pi'], true).targets).toEqual(['claude', 'pi']);
|
||||
});
|
||||
|
||||
it('reads back the skills target of a command it builds, and nothing from other commands', () => {
|
||||
expect(serveSkillsTarget(splitCommand(serveSkillsCommand('claude', true)))).toBe('claude');
|
||||
expect(serveSkillsTarget(splitCommand(serveSkillsCommand('', false)))).toBe('');
|
||||
// A project's name may hold spaces: its target must survive as one word.
|
||||
expect(serveSkillsTarget(splitCommand(serveSkillsCommand('my app@claude', false)))).toBe('my app@claude');
|
||||
expect(serveSkillsTarget(['skillshare', 'mcp', 'serve', '--http', ':8765'])).toBeUndefined();
|
||||
expect(serveSkillsTarget(['npx', 'skillshare', 'mcp', 'serve'])).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,6 +38,29 @@ export function initialServerDraft(server: MCPServer | undefined, name: string,
|
||||
};
|
||||
}
|
||||
|
||||
/** How a new server is entered: fields, a pasted configuration, or Skillshare itself (`skillshare mcp serve`). */
|
||||
export type AddMode = 'form' | 'paste' | 'serve';
|
||||
|
||||
/** The command that serves skills over MCP: every enabled skill, or those of one skills target. */
|
||||
export const serveSkillsCommand = (target: string, project: boolean) =>
|
||||
joinCommand(['skillshare', 'mcp', 'serve', ...(target ? ['--target', target] : []), ...(project ? ['-p'] : [])]);
|
||||
|
||||
/** The skills target a `skillshare mcp serve` command serves ('' for every skill), or undefined for any other command. */
|
||||
export function serveSkillsTarget(words: string[]): string | undefined {
|
||||
if (words[0] !== 'skillshare' || words[1] !== 'mcp' || words[2] !== 'serve') return undefined;
|
||||
let target = '';
|
||||
for (let i = 3; i < words.length; i++) {
|
||||
if (words[i] === '-p' || words[i] === '--project') continue;
|
||||
if (words[i] === '--target' && i + 1 < words.length) { target = words[++i]; continue; }
|
||||
return undefined;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/** Whether a source server runs `skillshare mcp serve`, so the dialog edits it in the Skillshare tab. */
|
||||
export const isServeCommand = (server?: MCPServer) =>
|
||||
Boolean(server?.command && !server.url && serveSkillsTarget([server.command, ...(server.args ?? [])]) !== undefined);
|
||||
|
||||
/** Why Pi's other settings cannot be saved, or '' when they can. */
|
||||
export const piOptionsError = (options: ReturnType<typeof parsePiOptions>, t: ReturnType<typeof useT>) =>
|
||||
options.invalid ? t('mcp.piOptionsInvalid')
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "Ausschalten für",
|
||||
"mcp.command": "Befehl",
|
||||
"mcp.commandHint": "Das Programm und seine Argumente, so wie du sie im Terminal eingeben würdest.",
|
||||
"mcp.serve.intro": "Stellt deine Skills per MCP einem Agent bereit, der sie nicht per Sync erhält, etwa einem hinter einem MCP-Gateway. Der Agent startet skillshare selbst; du musst nichts weiter installieren. Agents mit der MCP Skills extension laden sie als Skills; andere erhalten Werkzeuge, um sie aufzulisten und zu lesen.",
|
||||
"mcp.serve.which": "Bereitgestellte Skills",
|
||||
"mcp.serve.all": "Alle aktivierten Skills",
|
||||
"mcp.serve.like": "Wie Ziel {name}",
|
||||
"mcp.serve.runs": "Führt aus",
|
||||
"mcp.serve.runsHint": "Skills, die du installierst, aktualisierst oder deaktivierst, erscheinen nach wenigen Sekunden, ohne Neustart.",
|
||||
"mcp.serve.synced": "synct Skills",
|
||||
"mcp.serve.twice": "{names} erhalten diese Skills schon per Sync und sähen jeden doppelt.",
|
||||
"mcp.environment": "Umgebung",
|
||||
"mcp.environmentHint": "Wähle „Aus der Umgebung“ für Geheimnisse: Das Tool liest sie beim Start, sodass sie nie in Konfigurationsdateien landen.",
|
||||
"mcp.envName": "Variablenname",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "Turn it off for",
|
||||
"mcp.command": "Command",
|
||||
"mcp.commandHint": "The program and its arguments, as you would type them in a terminal.",
|
||||
"mcp.serve.intro": "Serve your skills over MCP to an Agent that doesn't get them by sync, such as one behind an MCP gateway. The Agent starts skillshare itself; there is nothing else to install. Agents with the MCP Skills extension load them as skills; others get tools to list and read them.",
|
||||
"mcp.serve.which": "Skills to serve",
|
||||
"mcp.serve.all": "All enabled skills",
|
||||
"mcp.serve.like": "Same as target {name}",
|
||||
"mcp.serve.runs": "Runs",
|
||||
"mcp.serve.runsHint": "Skills you install, update or disable show up within a few seconds; no restart needed.",
|
||||
"mcp.serve.synced": "syncs skills",
|
||||
"mcp.serve.twice": "{names} already get these skills by sync, so they would see each one twice.",
|
||||
"mcp.environment": "Environment",
|
||||
"mcp.environmentHint": "Pick From environment for secrets: the tool reads them when it starts, so they are never written into config files.",
|
||||
"mcp.envName": "Variable name",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "Desactivarlo en",
|
||||
"mcp.command": "Comando",
|
||||
"mcp.commandHint": "El programa y sus argumentos, tal como los escribirías en una terminal.",
|
||||
"mcp.serve.intro": "Ofrece tus skills por MCP a un Agent que no las recibe por sincronización, por ejemplo uno detrás de una pasarela MCP. El Agent inicia skillshare por sí mismo; no hay nada más que instalar. Los Agents con la MCP Skills extension las cargan como skills; los demás reciben herramientas para listarlas y leerlas.",
|
||||
"mcp.serve.which": "Skills que se ofrecen",
|
||||
"mcp.serve.all": "Todas las skills activadas",
|
||||
"mcp.serve.like": "Igual que el destino {name}",
|
||||
"mcp.serve.runs": "Ejecuta",
|
||||
"mcp.serve.runsHint": "Las skills que instalas, actualizas o desactivas aparecen en pocos segundos, sin reiniciar.",
|
||||
"mcp.serve.synced": "sincroniza skills",
|
||||
"mcp.serve.twice": "{names} ya reciben estas skills por sincronización, así que verían cada una dos veces.",
|
||||
"mcp.environment": "Entorno",
|
||||
"mcp.environmentHint": "Elige «Desde el entorno» para los secretos: la herramienta los lee al iniciarse y nunca se escriben en archivos de configuración.",
|
||||
"mcp.envName": "Nombre de la variable",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "خاموش کردن برای",
|
||||
"mcp.command": "فرمان",
|
||||
"mcp.commandHint": "برنامه و آرگومانهایش، همانطور که در ترمینال مینویسید.",
|
||||
"mcp.serve.intro": "اسکیلهای خود را از راه MCP به Agentی ارائه کنید که آنها را با همگامسازی دریافت نمیکند، مانند Agentی پشت یک دروازهٔ MCP. خود Agent برنامهٔ skillshare را اجرا میکند و نیازی به نصب چیز دیگری نیست. Agentهایی که از MCP Skills extension پشتیبانی میکنند آنها را بهصورت اسکیل بارگذاری میکنند؛ بقیه ابزارهایی برای فهرست کردن و خواندن آنها میگیرند.",
|
||||
"mcp.serve.which": "اسکیلهای ارائهشده",
|
||||
"mcp.serve.all": "همهٔ اسکیلهای فعال",
|
||||
"mcp.serve.like": "مانند مقصد {name}",
|
||||
"mcp.serve.runs": "اجرا میکند",
|
||||
"mcp.serve.runsHint": "اسکیلهایی که نصب، بهروزرسانی یا غیرفعال میکنید ظرف چند ثانیه نمایش داده میشوند و نیازی به راهاندازی دوباره نیست.",
|
||||
"mcp.serve.synced": "اسکیلها همگام است",
|
||||
"mcp.serve.twice": "{names} این اسکیلها را از راه همگامسازی دریافت میکند، پس هر کدام را دو بار میبیند.",
|
||||
"mcp.environment": "محیط",
|
||||
"mcp.environmentHint": "برای مقادیر محرمانه «از محیط» را انتخاب کنید: ابزار هنگام اجرا آنها را میخواند و هرگز در فایلهای پیکربندی نوشته نمیشوند.",
|
||||
"mcp.envName": "نام متغیر",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "Le désactiver pour",
|
||||
"mcp.command": "Commande",
|
||||
"mcp.commandHint": "Le programme et ses arguments, comme vous les tapez dans un terminal.",
|
||||
"mcp.serve.intro": "Fournit vos skills par MCP à un Agent qui ne les reçoit pas par synchronisation, par exemple derrière une passerelle MCP. L'Agent lance skillshare lui-même ; rien d'autre à installer. Les Agents compatibles avec la MCP Skills extension les chargent comme skills ; les autres reçoivent des outils pour les lister et les lire.",
|
||||
"mcp.serve.which": "Skills fournies",
|
||||
"mcp.serve.all": "Toutes les skills activées",
|
||||
"mcp.serve.like": "Comme la cible {name}",
|
||||
"mcp.serve.runs": "Exécute",
|
||||
"mcp.serve.runsHint": "Les skills que vous installez, mettez à jour ou désactivez apparaissent en quelques secondes, sans redémarrage.",
|
||||
"mcp.serve.synced": "synchronise les skills",
|
||||
"mcp.serve.twice": "{names} reçoivent déjà ces skills par synchronisation et verraient chacune en double.",
|
||||
"mcp.environment": "Environnement",
|
||||
"mcp.environmentHint": "Choisissez « Depuis l’environnement » pour les secrets : l’outil les lit au démarrage, ils ne sont jamais écrits dans les fichiers de configuration.",
|
||||
"mcp.envName": "Nom de la variable",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "Matikan untuk",
|
||||
"mcp.command": "Perintah",
|
||||
"mcp.commandHint": "Program dan argumennya, seperti yang Anda ketik di terminal.",
|
||||
"mcp.serve.intro": "Sajikan skill Anda lewat MCP ke Agent yang tidak menerimanya lewat sinkronisasi, misalnya Agent di balik gateway MCP. Agent menjalankan skillshare sendiri; tidak ada lagi yang perlu dipasang. Agent dengan MCP Skills extension memuatnya sebagai skill; Agent lain mendapat alat untuk menampilkan dan membacanya.",
|
||||
"mcp.serve.which": "Skill yang disajikan",
|
||||
"mcp.serve.all": "Semua skill yang aktif",
|
||||
"mcp.serve.like": "Sama seperti target {name}",
|
||||
"mcp.serve.runs": "Menjalankan",
|
||||
"mcp.serve.runsHint": "Skill yang Anda pasang, perbarui, atau nonaktifkan muncul dalam beberapa detik tanpa memulai ulang.",
|
||||
"mcp.serve.synced": "sinkron skill",
|
||||
"mcp.serve.twice": "{names} sudah menerima skill ini lewat sinkronisasi, jadi setiap skill akan terlihat dua kali.",
|
||||
"mcp.environment": "Environment",
|
||||
"mcp.environmentHint": "Pilih Dari environment untuk rahasia: tool membacanya saat mulai, jadi tidak pernah ditulis ke file konfigurasi.",
|
||||
"mcp.envName": "Nama variabel",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "オフにする対象",
|
||||
"mcp.command": "コマンド",
|
||||
"mcp.commandHint": "ターミナルで入力するときと同じ、プログラムと引数。",
|
||||
"mcp.serve.intro": "同期でスキルを受け取らない Agent(MCP ゲートウェイの先にある Agent など)に、MCP でスキルを提供します。Agent が skillshare を自分で起動するので、ほかにインストールするものはありません。MCP Skills extension に対応した Agent はスキルとして読み込み、それ以外の Agent にはスキルを一覧・読み取るツールが提供されます。",
|
||||
"mcp.serve.which": "提供するスキル",
|
||||
"mcp.serve.all": "有効なすべてのスキル",
|
||||
"mcp.serve.like": "ターゲット {name} と同じ",
|
||||
"mcp.serve.runs": "実行するコマンド",
|
||||
"mcp.serve.runsHint": "スキルをインストール・更新・無効化すると、数秒で反映されます。再起動は不要です。",
|
||||
"mcp.serve.synced": "スキル同期済み",
|
||||
"mcp.serve.twice": "{names} は同期ですでにこれらのスキルを受け取っているため、それぞれが二重に表示されます。",
|
||||
"mcp.environment": "環境変数",
|
||||
"mcp.environmentHint": "秘密情報には「環境変数から」を選びます。ツールが起動時に読み取るため、設定ファイルには書き込まれません。",
|
||||
"mcp.envName": "変数名",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "끌 대상",
|
||||
"mcp.command": "명령",
|
||||
"mcp.commandHint": "터미널에 입력하듯 프로그램과 인수를 적으세요.",
|
||||
"mcp.serve.intro": "동기화로 Skills를 받지 않는 Agent(예: MCP 게이트웨이 뒤의 Agent)에 MCP로 Skills를 제공합니다. Agent가 skillshare를 직접 실행하므로 따로 설치할 것이 없습니다. MCP Skills extension을 지원하는 Agent는 Skills로 바로 불러오고, 다른 Agent는 Skills를 나열하고 읽는 도구를 받습니다.",
|
||||
"mcp.serve.which": "제공할 Skills",
|
||||
"mcp.serve.all": "활성화된 모든 Skills",
|
||||
"mcp.serve.like": "대상 {name}과 같게",
|
||||
"mcp.serve.runs": "실행 명령",
|
||||
"mcp.serve.runsHint": "Skills를 설치, 업데이트, 비활성화하면 몇 초 안에 반영됩니다. 다시 시작할 필요가 없습니다.",
|
||||
"mcp.serve.synced": "Skills 동기화됨",
|
||||
"mcp.serve.twice": "{names}은(는) 이미 동기화로 이 Skills를 받고 있어 각각 두 번 보입니다.",
|
||||
"mcp.environment": "환경 변수",
|
||||
"mcp.environmentHint": "비밀 값은 '환경 변수에서'를 선택하세요. 도구가 시작할 때 읽으므로 설정 파일에 기록되지 않습니다.",
|
||||
"mcp.envName": "변수 이름",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "Desligá-lo para",
|
||||
"mcp.command": "Comando",
|
||||
"mcp.commandHint": "O programa e seus argumentos, como você digitaria em um terminal.",
|
||||
"mcp.serve.intro": "Disponibiliza suas skills por MCP para um Agent que não as recebe por sincronização, como um atrás de um gateway MCP. O Agent inicia o skillshare sozinho; não há mais nada para instalar. Agents com a MCP Skills extension as carregam como skills; os demais recebem ferramentas para listá-las e lê-las.",
|
||||
"mcp.serve.which": "Skills disponibilizadas",
|
||||
"mcp.serve.all": "Todas as skills ativadas",
|
||||
"mcp.serve.like": "Igual ao destino {name}",
|
||||
"mcp.serve.runs": "Executa",
|
||||
"mcp.serve.runsHint": "Skills que você instala, atualiza ou desativa aparecem em poucos segundos, sem reiniciar.",
|
||||
"mcp.serve.synced": "sincroniza skills",
|
||||
"mcp.serve.twice": "{names} já recebem essas skills por sincronização, então veriam cada uma duas vezes.",
|
||||
"mcp.environment": "Ambiente",
|
||||
"mcp.environmentHint": "Escolha Do ambiente para segredos: a ferramenta os lê ao iniciar, então nunca são gravados nos arquivos de configuração.",
|
||||
"mcp.envName": "Nome da variável",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "在这些 Agent 关闭",
|
||||
"mcp.command": "命令",
|
||||
"mcp.commandHint": "程序及其参数,写法与在终端中输入时相同。",
|
||||
"mcp.serve.intro": "通过 MCP 把你的 Skill 提供给没有通过同步获得 Skill 的 Agent,例如 MCP gateway 后面的 Agent。Agent 会自己启动 skillshare,无需另外安装。支持 MCP Skills extension 的 Agent 会直接作为 Skill 加载,其他 Agent 会获得列出和读取 Skill 的工具。",
|
||||
"mcp.serve.which": "提供哪些 Skill",
|
||||
"mcp.serve.all": "所有已启用的 Skill",
|
||||
"mcp.serve.like": "与目标 {name} 相同",
|
||||
"mcp.serve.runs": "将执行",
|
||||
"mcp.serve.runsHint": "安装、更新或停用 Skill 后,几秒内就会生效,无需重启。",
|
||||
"mcp.serve.synced": "已同步 Skill",
|
||||
"mcp.serve.twice": "{names} 已经通过同步获得这些 Skill,再连接会每个看到两份。",
|
||||
"mcp.environment": "环境变量",
|
||||
"mcp.environmentHint": "机密信息请选择“来自环境变量”:工具启动时读取,不会写入配置文件。",
|
||||
"mcp.envName": "变量名",
|
||||
|
||||
@@ -99,6 +99,14 @@
|
||||
"mcp.offTargets": "在這些 Agent 關閉",
|
||||
"mcp.command": "指令",
|
||||
"mcp.commandHint": "程式和它的參數,寫法跟在終端機輸入時一樣。",
|
||||
"mcp.serve.intro": "透過 MCP 把你的 skills 提供給沒有透過同步拿到 skills 的 Agent,例如 MCP gateway 後面的 Agent。Agent 會自己啟動 skillshare,不用另外安裝。支援 MCP Skills extension 的 Agent 會直接載入成 skills,其他 Agent 則會拿到列出和讀取 skills 的工具。",
|
||||
"mcp.serve.which": "提供哪些 skills",
|
||||
"mcp.serve.all": "所有啟用中的 skills",
|
||||
"mcp.serve.like": "跟目標 {name} 一樣",
|
||||
"mcp.serve.runs": "會執行",
|
||||
"mcp.serve.runsHint": "安裝、更新或停用 skills 後,幾秒內就會生效,不用重新啟動。",
|
||||
"mcp.serve.synced": "已同步 skills",
|
||||
"mcp.serve.twice": "{names} 已經透過同步拿到這些 skills,再接上會每個看到兩份。",
|
||||
"mcp.environment": "環境變數",
|
||||
"mcp.environmentHint": "機密資訊請選「來自環境變數」:工具啟動時才讀取,不會寫進設定檔。",
|
||||
"mcp.envName": "變數名稱",
|
||||
|
||||
@@ -26,6 +26,7 @@ import { MCPConfigDialog } from '../components/mcp/MCPConfigView';
|
||||
import MCPRemoveDialog from '../components/mcp/MCPRemoveDialog';
|
||||
import MCPRestoreDialog from '../components/mcp/MCPRestoreDialog';
|
||||
import MCPServerDialog from '../components/mcp/MCPServerDialog';
|
||||
import { isServeCommand, type AddMode } from '../components/mcp/mcpServerDraft';
|
||||
import { buildMatrix, canImportConflict, describeError, describeMessage, isShadowed, isResolvable, mcpOrder, projectOf, targetLabel, writes, type MCPChange } from '../components/mcp/mcpView';
|
||||
import { MCPTargetOrder } from '../components/mcp/targetOrder';
|
||||
import { useMCPToggle } from '../components/mcp/useMCPToggle';
|
||||
@@ -195,8 +196,11 @@ function MCPContent({ data, model, order, allFiles, onShowAll, busy, onToggle, o
|
||||
);
|
||||
}
|
||||
|
||||
function MCPEditDialog({ data, model, editing, addingOff, addMode, onMode, onClose, onSaved }: { data: MCPList; model: PageModel; editing: string; addingOff: boolean; addMode: 'form' | 'paste'; onMode: (mode: 'form' | 'paste') => void; onClose: () => void; onSaved: () => void }) {
|
||||
function MCPEditDialog({ data, model, editing, addingOff, addMode, onMode, onClose, onSaved }: { data: MCPList; model: PageModel; editing: string; addingOff: boolean; addMode: AddMode; onMode: (mode: AddMode) => void; onClose: () => void; onSaved: () => void }) {
|
||||
const { servers, defaults, files } = model;
|
||||
const server = editing ? servers[editing] : undefined;
|
||||
// skillshare mcp serve has its own tab; an edit of such a server opens it again.
|
||||
const serve = editing === '' ? addMode === 'serve' : isServeCommand(server);
|
||||
return (
|
||||
editing === '' && addMode === 'paste' ? (
|
||||
<MCPImportDialog
|
||||
@@ -211,8 +215,10 @@ function MCPEditDialog({ data, model, editing, addingOff, addMode, onMode, onClo
|
||||
/>
|
||||
) : (
|
||||
<MCPServerDialog
|
||||
key={addMode}
|
||||
off={editing === '' && addingOff}
|
||||
initial={editing ? { name: editing, server: servers[editing] } : undefined}
|
||||
serve={serve}
|
||||
initial={editing && server ? { name: editing, server } : undefined}
|
||||
defaultTargets={defaults}
|
||||
existingNames={Object.keys(servers)}
|
||||
availableTargets={files}
|
||||
@@ -299,7 +305,7 @@ export default function MCPPage() {
|
||||
const [addingOff, setAddingOff] = useState(false); // the new entry is a switch, not a server
|
||||
const [editing, setEditing] = useState<string | null>(null); // '' adds a new server
|
||||
// Adding takes two shapes: fill the fields, or paste a snippet. Both end up saving one source server.
|
||||
const [addMode, setAddMode] = useState<'form' | 'paste'>('form');
|
||||
const [addMode, setAddMode] = useState<AddMode>('form');
|
||||
const [importing, setImporting] = useState<ImportRequest | null>(null);
|
||||
const [removing, setRemoving] = useState('');
|
||||
const [viewing, setViewing] = useState('');
|
||||
|
||||
@@ -52,7 +52,10 @@ a configuration. The paste side also loads a file, which is the browser's
|
||||
equivalent of `mcp import --file`. Pasted JSON is recognized automatically; for
|
||||
TOML, choose whether it came from Codex or Grok. When the paste holds one server
|
||||
and Pi is ticked, the dialog also shows the Pi settings of the form: tool exposure and
|
||||
other Pi settings. **Import from a target** is
|
||||
other Pi settings. The **Skillshare** tab adds `skillshare mcp serve`, which
|
||||
[serves your skills over MCP](/docs/reference/commands/mcp#serve-skills-over-mcp) to an
|
||||
Agent that does not get them by sync: choose which skills, tick the Agents, and it marks
|
||||
the Agents that already sync skills and would see them twice. **Import from a target** is
|
||||
separate and reads the servers an installed Agent already has. Either way the
|
||||
dashboard uses the same source, validation, preview and conflict rules as the
|
||||
CLI. **Sync MCP**, in the MCP page's Sync box, writes the MCP config files only. The
|
||||
|
||||
@@ -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,9 @@ 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) |
|
||||
| `--tls-cert FILE`, `--tls-key FILE` | With `serve --http`: serve HTTPS with this PEM certificate and key; required off loopback |
|
||||
| `--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 +771,99 @@ 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 \
|
||||
--tls-cert cert.pem --tls-key key.pem # HTTPS for other machines
|
||||
```
|
||||
|
||||
`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`
|
||||
does not begin with its frontmatter, when its `name` breaks the Agent Skills naming
|
||||
rules or differs from its directory name (for example after `install --name`), when
|
||||
its description is missing or over 1,024 characters or its `compatibility` over 500,
|
||||
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` and HTTPS through `--tls-cert` and `--tls-key`, so the token
|
||||
never crosses the network in plain text; when the token is set, every request must
|
||||
send `Authorization: Bearer <token>`. To use a TLS proxy instead, bind a loopback
|
||||
address such as `127.0.0.1:8765` and let the proxy terminate TLS.
|
||||
- **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` with a certificate where the
|
||||
skills are and point a remote server at it. Keep the token in an environment variable:
|
||||
|
||||
```yaml
|
||||
mcp:
|
||||
servers:
|
||||
skillshare:
|
||||
url: https://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
|
||||
|
||||
Reference in New Issue
Block a user