-
Notifications
You must be signed in to change notification settings - Fork 976
Expand file tree
/
Copy pathinit.go
More file actions
432 lines (378 loc) · 11.1 KB
/
Copy pathinit.go
File metadata and controls
432 lines (378 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package commands
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/modelcontextprotocol/registry/pkg/model"
"github.com/spf13/cobra"
)
func init() {
mcpPublisherCmd.AddCommand(initCmd)
}
var initCmd = &cobra.Command{
Use: "init",
Short: "Create a server.json file template",
Long: `This command creates a server.json file in the current directory with
auto-detected values from your project (package.json, git remote, etc.).
After running init, edit the generated server.json to customize your
server's metadata before publishing.`,
RunE: runInitCmd,
}
var runInitCmd = func(_ *cobra.Command, _ []string) error {
// Check if server.json already exists
if _, err := os.Stat("server.json"); err == nil {
return errors.New("server.json already exists")
}
// Detect if we're in a subdirectory of the git repository
subfolder := detectSubfolder()
// Try to detect values from environment
name := detectServerName(subfolder)
description := detectDescription()
version := "1.0.0"
repoURL := detectRepoURL()
repoSource := MethodGitHub
if repoURL != "" && !strings.Contains(repoURL, "github.com") {
if strings.Contains(repoURL, "gitlab.com") {
repoSource = "gitlab"
} else {
repoSource = "git"
}
}
packageType := detectPackageType()
packageIdentifier := detectPackageIdentifier(name, packageType)
// Create example environment variables
envVars := []model.KeyValueInput{
{
Name: "YOUR_API_KEY",
InputWithVariables: model.InputWithVariables{
Input: model.Input{
Description: "Your API key for the service",
IsRequired: true,
IsSecret: true,
Format: model.FormatString,
},
},
},
}
// Create the server structure
server := createServerJSON(
model.CurrentSchemaURL, name, description, version, repoURL, repoSource, subfolder,
packageType, packageIdentifier, version, envVars,
)
// Write to file
jsonData, err := json.MarshalIndent(server, "", " ")
if err != nil {
return fmt.Errorf("error marshaling JSON: %w", err)
}
err = os.WriteFile("server.json", jsonData, 0600)
if err != nil {
return fmt.Errorf("error writing file: %w", err)
}
_, _ = fmt.Fprintln(os.Stdout, "Created server.json")
_, _ = fmt.Fprintln(os.Stdout, "\nEdit server.json to update:")
_, _ = fmt.Fprintln(os.Stdout, " • Server name and description")
_, _ = fmt.Fprintln(os.Stdout, " • Package details")
_, _ = fmt.Fprintln(os.Stdout, " • Environment variables")
_, _ = fmt.Fprintln(os.Stdout, "\nThen publish with:")
_, _ = fmt.Fprintln(os.Stdout, " mcp-publisher login github # or your preferred auth method")
_, _ = fmt.Fprintln(os.Stdout, " mcp-publisher publish")
return nil
}
func detectSubfolder() string {
// Get current working directory
cwd, err := os.Getwd()
if err != nil {
return ""
}
// Find git repository root
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
cmd.Dir = cwd
output, err := cmd.Output()
if err != nil {
// Not in a git repository
return ""
}
gitRoot := strings.TrimSpace(string(output))
// Clean the paths to ensure proper comparison
gitRoot = filepath.Clean(gitRoot)
cwd = filepath.Clean(cwd)
// If we're in the root, no subfolder
if gitRoot == cwd {
return ""
}
// Check if cwd is actually within gitRoot
if !strings.HasPrefix(cwd, gitRoot) {
return ""
}
// Calculate relative path from git root to current directory
relPath, err := filepath.Rel(gitRoot, cwd)
if err != nil {
return ""
}
// Convert to forward slashes for consistency (important for cross-platform)
return filepath.ToSlash(relPath)
}
func getNameFromPackageJSON() string {
data, err := os.ReadFile("package.json")
if err != nil {
return ""
}
var pkg map[string]any
if err := json.Unmarshal(data, &pkg); err != nil {
return ""
}
name, ok := pkg["name"].(string)
if !ok || name == "" {
return ""
}
// Convert npm package name to MCP server name
// @org/package -> io.npm.org/package
if strings.HasPrefix(name, "@") {
parts := strings.Split(name[1:], "/")
if len(parts) == 2 {
return fmt.Sprintf("io.github.%s/%s", parts[0], parts[1])
}
}
return fmt.Sprintf("io.github.<your-username>/%s", name)
}
func detectServerName(subfolder string) string {
// Try to get from git remote
repoURL := detectRepoURL()
if repoURL != "" && strings.Contains(repoURL, "github.com") {
name := buildGitHubServerName(repoURL, subfolder)
if name != "" {
return name
}
}
// Try to get from package.json
name := getNameFromPackageJSON()
if name != "" {
return name
}
// Use current directory name as fallback
if cwd, err := os.Getwd(); err == nil {
return fmt.Sprintf("com.example/%s", filepath.Base(cwd))
}
return "com.example/my-mcp-server"
}
func buildGitHubServerName(repoURL, subfolder string) string {
parts := strings.Split(repoURL, "/")
if len(parts) < 5 {
return ""
}
owner := parts[3]
repo := strings.TrimSuffix(parts[4], ".git")
// If we're in a subdirectory, use the current folder name
if subfolder != "" {
folderName := filepath.Base(subfolder)
return fmt.Sprintf("io.github.%s/%s", owner, folderName)
}
return fmt.Sprintf("io.github.%s/%s", owner, repo)
}
func detectDescription() string {
// Try to get from package.json
if data, err := os.ReadFile("package.json"); err == nil {
var pkg map[string]any
if json.Unmarshal(data, &pkg) == nil {
if desc, ok := pkg["description"].(string); ok && desc != "" {
return desc
}
}
}
return "An MCP server that provides [describe what your server does]"
}
func detectRepoURL() string {
sanitizeURL := func(url string) string {
return strings.TrimPrefix(url, "git+")
}
// Try git remote
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", "remote", "get-url", "origin")
if output, err := cmd.Output(); err == nil {
url := strings.TrimSpace(string(output))
// Convert SSH URL to HTTPS if needed
if strings.HasPrefix(url, "git@github.com:") {
url = strings.Replace(url, "git@github.com:", "https://github.com/", 1)
}
url = strings.TrimSuffix(url, ".git")
return url
}
// Try package.json repository field
if data, err := os.ReadFile("package.json"); err == nil {
var pkg map[string]any
if json.Unmarshal(data, &pkg) == nil {
if repo, ok := pkg["repository"].(map[string]any); ok {
if url, ok := repo["url"].(string); ok {
return sanitizeURL(strings.TrimSuffix(url, ".git"))
}
}
if repo, ok := pkg["repository"].(string); ok {
return sanitizeURL(strings.TrimSuffix(repo, ".git"))
}
}
}
return "https://github.com/YOUR_USERNAME/YOUR_REPO"
}
func detectPackageType() string {
// Check for package.json
if _, err := os.Stat("package.json"); err == nil {
return model.RegistryTypeNPM
}
// Check for pyproject.toml or setup.py
if _, err := os.Stat("pyproject.toml"); err == nil {
return model.RegistryTypePyPI
}
if _, err := os.Stat("setup.py"); err == nil {
return model.RegistryTypePyPI
}
// Check for Dockerfile
if _, err := os.Stat("Dockerfile"); err == nil {
return model.RegistryTypeOCI
}
// Default to npm as most common
return model.RegistryTypeNPM
}
func detectPackageIdentifier(serverName string, packageType string) string {
switch packageType {
case model.RegistryTypeNPM:
// Try to get from package.json
if data, err := os.ReadFile("package.json"); err == nil {
var pkg map[string]any
if json.Unmarshal(data, &pkg) == nil {
if name, ok := pkg["name"].(string); ok && name != "" {
return name
}
}
}
// Convert server name to npm package name
if strings.HasPrefix(serverName, "io.github.") {
parts := strings.Split(serverName, "/")
if len(parts) == 2 {
owner := strings.TrimPrefix(parts[0], "io.github.")
return fmt.Sprintf("@%s/%s", owner, parts[1])
}
}
return "@your-org/your-package"
case model.RegistryTypePyPI:
// Try to get from pyproject.toml or setup.py
if data, err := os.ReadFile("pyproject.toml"); err == nil {
// Simple extraction - could be improved with proper TOML parser
lines := strings.Split(string(data), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "name") && strings.Contains(line, "=") {
parts := strings.Split(line, "=")
if len(parts) >= 2 {
name := strings.Trim(parts[1], " \"'")
if name != "" {
return name
}
}
}
}
}
return "your-package"
case model.RegistryTypeOCI:
// Use a sensible default
if strings.Contains(serverName, "/") {
parts := strings.Split(serverName, "/")
return parts[len(parts)-1]
}
return "your-image"
default:
return "your-package"
}
}
func createServerJSON(
currentSchema, name, description, version, repoURL, repoSource, subfolder,
packageType, packageIdentifier, packageVersion string,
envVars []model.KeyValueInput,
) apiv0.ServerJSON {
// Create package based on type
var pkg model.Package
switch packageType {
case model.RegistryTypeNPM:
pkg = model.Package{
RegistryType: model.RegistryTypeNPM,
Identifier: packageIdentifier,
Version: packageVersion,
EnvironmentVariables: envVars,
Transport: model.Transport{
Type: model.TransportTypeStdio,
},
}
case model.RegistryTypePyPI:
pkg = model.Package{
RegistryType: model.RegistryTypePyPI,
Identifier: packageIdentifier,
Version: packageVersion,
EnvironmentVariables: envVars,
Transport: model.Transport{
Type: model.TransportTypeStdio,
},
}
case model.RegistryTypeOCI:
// OCI packages use canonical references: registry/namespace/image:tag
// Format: docker.io/username/image:version
canonicalRef := fmt.Sprintf("docker.io/%s:%s", packageIdentifier, packageVersion)
pkg = model.Package{
RegistryType: model.RegistryTypeOCI,
Identifier: canonicalRef,
// No Version field for OCI - it's embedded in the canonical reference
EnvironmentVariables: envVars,
Transport: model.Transport{
Type: model.TransportTypeStdio,
},
}
case "url":
pkg = model.Package{
RegistryType: "url",
Identifier: packageIdentifier,
Version: packageVersion,
EnvironmentVariables: envVars,
Transport: model.Transport{
Type: model.TransportTypeStdio,
},
}
default:
pkg = model.Package{
RegistryType: packageType,
Identifier: packageIdentifier,
Version: packageVersion,
EnvironmentVariables: envVars,
Transport: model.Transport{
Type: model.TransportTypeStdio,
},
}
}
// Create repository with optional subfolder
var repo *model.Repository
if repoURL != "" && repoSource != "" {
repo = &model.Repository{
URL: repoURL,
Source: repoSource,
}
// Only set subfolder if we're actually in a subdirectory
if subfolder != "" {
repo.Subfolder = subfolder
}
}
// Create server structure
return apiv0.ServerJSON{
Schema: currentSchema,
Name: name,
Description: description,
Repository: repo,
Version: version,
Packages: []model.Package{pkg},
}
}