feat(plugin): 插件热安装(MCP server) — POST /admin/plugins/install 连接+发现+注册工具进registry+落盘plugins.json
- capability/plugin/manager.go: Manager(Install/Uninstall/List/Restore/Close); Install=连接+发现+mcp:name注册工具,失败不落盘; holder持有*mcp.Registry; boot Restore重装
- config/runtimeconfig/plugins.go: PluginConfig(Normalize/Validate), LoadPlugins/SavePlugins(0600+tmp+rename)/Upsert/Delete/Masked(apiKey+敏感env掩码)
- mcp: MCPConfig加APIKey/Env, http/sse Bearer应用, stdio子进程env合并; registry.ToolNames()
- gateway: adminPluginInstall/Uninstall/ListInstalledPlugins; Deps.Plugins注入
- cmd/cyrene/plugins.go: wirePlugins(boot Restore+close)
- 契约: body{kind:mcp,name,config{transport, endpoint?/command?,args?,apiKey?,env?}} → {installed,name,kind,transport,toolCount}; 失败502不落盘/非法400/未注入501; 卸载连带unregister+删配置
- 测试(manager/plugins/admin/mcp_auth/组合根), build/vet/test绿+3平台交叉编译
- Docs/api-client v0.28 + api-reference install=501改真实; .gitignore加plugins.json
- 前端api.ts仍发旧body(无config)会400, 面板安装表单待后续
This commit is contained in:
1 parent
53002f1e11
commit
70c9fba529
20 files changed
+1885
-57
No files matched your search
@@ -145,6 +145,7 @@ func (s *streamableHTTPTransport) post(ctx context.Context, body []byte) (*http.
|
||||
func (s *streamableHTTPTransport) applyHeaders(req *http.Request) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
s.applyAuth(req)
|
||||
s.mu.Lock()
|
||||
session := s.session
|
||||
proto := ""
|
||||
@@ -160,6 +161,14 @@ func (s *streamableHTTPTransport) applyHeaders(req *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// applyAuth sets the bearer credential an authenticated server requires. It is
|
||||
// a no-op when the config carries no API key.
|
||||
func (s *streamableHTTPTransport) applyAuth(req *http.Request) {
|
||||
if s.cfg.APIKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+s.cfg.APIKey)
|
||||
}
|
||||
}
|
||||
|
||||
// captureSession stores a session id returned by the server.
|
||||
func (s *streamableHTTPTransport) captureSession(resp *http.Response) {
|
||||
if sid := resp.Header.Get(mcpSessionIDHeader); sid != "" {
|
||||
@@ -321,6 +330,7 @@ func (s *streamableHTTPTransport) readStandalone(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
s.applyAuth(req)
|
||||
s.mu.Lock()
|
||||
session := s.session
|
||||
proto := ""
|
||||
|
||||
@@ -149,6 +149,12 @@ type MCPConfig struct {
|
||||
// TransportType selects the transport explicitly: "stdio", "sse" or
|
||||
// "http" (Streamable HTTP). Empty means infer from Command/URL.
|
||||
TransportType string `env:"MCP_TRANSPORT"`
|
||||
// APIKey is the bearer credential sent to an http/sse server as an
|
||||
// Authorization header. Empty means the server needs no auth.
|
||||
APIKey string `env:"MCP_API_KEY"`
|
||||
// Env is extra environment for a stdio subprocess, merged over the parent
|
||||
// process environment (extra keys win). It is ignored by the HTTP transports.
|
||||
Env map[string]string `env:"MCP_ENV"`
|
||||
// Enabled reports whether this server should be activated at startup.
|
||||
Enabled bool `env:"MCP_ENABLED"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnvWith_OverridesAndPreserves(t *testing.T) {
|
||||
t.Parallel()
|
||||
base := []string{"PATH=/usr/bin", "HOME=/root"}
|
||||
got := envWith(base, map[string]string{"HOME": "/tmp", "MCP_TOKEN": "abc"})
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("len = %d, want 3 (%v)", len(got), got)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, kv := range got {
|
||||
seen[kv] = true
|
||||
}
|
||||
if !seen["PATH=/usr/bin"] || !seen["HOME=/tmp"] || !seen["MCP_TOKEN=abc"] {
|
||||
t.Fatalf("merged env = %v", got)
|
||||
}
|
||||
if len(envWith(base, nil)) != len(base) {
|
||||
t.Fatal("empty extra changed the base environment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransport_SendsAPIKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := make(chan string, 1)
|
||||
srv := httpTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
got <- r.Header.Get("Authorization")
|
||||
httpJSONResponse(w, r)
|
||||
})
|
||||
defer srv.Close()
|
||||
tr := newHTTPTransport(MCPConfig{Name: "s", URL: srv.URL, APIKey: "sk-1234"}, defaultLogger())
|
||||
defer tr.Close()
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if err := tr.Call(context.Background(), "tools/list", nil, &listToolsResult{}); err != nil {
|
||||
t.Fatalf("Call: %v", err)
|
||||
}
|
||||
if auth := <-got; auth != "Bearer sk-1234" {
|
||||
t.Fatalf("Authorization = %q, want bearer key", auth)
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,14 @@ func (r *Registry) refresh() {
|
||||
r.log.Info("mcp tools refreshed", "name", r.mcp.cfg.Name, "count", len(r.names))
|
||||
}
|
||||
|
||||
// ToolNames returns a copy of the tool names this registry registered, in
|
||||
// registration order. It is empty before Register succeeds.
|
||||
func (r *Registry) ToolNames() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]string(nil), r.names...)
|
||||
}
|
||||
|
||||
// Unregister removes every tool this registry previously registered and closes
|
||||
// the underlying client. It is safe to call multiple times.
|
||||
func (r *Registry) Unregister(ctx context.Context) error {
|
||||
|
||||
@@ -71,6 +71,7 @@ func (s *sseTransport) Start(ctx context.Context) error {
|
||||
return fmt.Errorf("mcp sse get: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
s.applyAuth(req)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mcp sse connect %s: %w", s.cfg.URL, err)
|
||||
@@ -187,6 +188,7 @@ func (s *sseTransport) Call(ctx context.Context, method string, params any, resu
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Accept", "application/json")
|
||||
s.applyAuth(httpReq)
|
||||
resp, err := http.DefaultClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mcp sse %s post: %w", method, err)
|
||||
@@ -245,6 +247,7 @@ func (s *sseTransport) notify(ctx context.Context, method string, params any) er
|
||||
return fmt.Errorf("mcp notify %s: %w", method, err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
s.applyAuth(httpReq)
|
||||
resp, err := http.DefaultClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mcp notify %s: %w", method, err)
|
||||
@@ -254,6 +257,14 @@ func (s *sseTransport) notify(ctx context.Context, method string, params any) er
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyAuth sets the bearer credential an authenticated server requires. It is
|
||||
// a no-op when the config carries no API key.
|
||||
func (s *sseTransport) applyAuth(req *http.Request) {
|
||||
if s.cfg.APIKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+s.cfg.APIKey)
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes the SSE stream and any pending responses.
|
||||
func (s *sseTransport) Close() error {
|
||||
s.closeOnce.Do(func() {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -51,6 +52,7 @@ func (s *stdioTransport) Start(ctx context.Context) error {
|
||||
return fmt.Errorf("mcp stdio: %w", ErrNoTransport)
|
||||
}
|
||||
cmd := exec.Command(s.cfg.Command, s.cfg.Args...)
|
||||
cmd.Env = envWith(os.Environ(), s.cfg.Env)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return fmt.Errorf("mcp stdio stdin: %w", err)
|
||||
@@ -200,3 +202,24 @@ func (l *lineRPC) notify(ctx context.Context, method string, params any) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// envWith returns base with extra merged over it (an extra key overrides a
|
||||
// same-named base entry). A nil/empty extra returns base unchanged.
|
||||
func envWith(base []string, extra map[string]string) []string {
|
||||
if len(extra) == 0 {
|
||||
return base
|
||||
}
|
||||
out := make([]string, 0, len(base)+len(extra))
|
||||
for _, kv := range base {
|
||||
if k, _, ok := strings.Cut(kv, "="); ok {
|
||||
if _, dup := extra[k]; dup {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, kv)
|
||||
}
|
||||
for k, v := range extra {
|
||||
out = append(out, k+"="+v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in new issue
Block a user