Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,24 @@ metorial-admin files upload ./logo.png --purpose organization_image
metorial-admin files upload ./build-context --purpose sandbox_image_build_context
```

### Personal integrations

A signed-in member of a claimed organization can connect an existing integration
and use its Magic MCP tools as their own consumer:

```sh
metorial-admin integrations personal setup <integration-id>
metorial-admin integrations personal status <catalog-item-id> <setup-session-id>
metorial-admin integrations personal wait <catalog-item-id> <setup-session-id>
metorial-admin integrations personal finish <catalog-item-id> <setup-session-id>
metorial-admin integrations personal tools <server-id>
```

Setup opens the browser and returns the IDs for resuming. Finish deploys and
verifies the connection. The CLI uses its existing sign-in and keeps the
short-lived consumer credential in memory.


## Skills

Both CLIs can edit Metorial skills. `metorial` works with the skills you can access in your portal; `metorial-admin skills` works with every skill in the instance.
Expand Down
6 changes: 4 additions & 2 deletions generator/src/join.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,14 @@ export let joinManifest = (input: {
throw new Error(`manifest command ${entry.path.join(' ')} is missing resource`);
}

let wanted = normalizeSdkPath(entry.resource);
let defaultResource = entry.resource;
let matches = publicEndpoints.filter(endpoint => {
let { resource, method } = splitResourceMethod(normalizeSdkPath(endpoint.sdkPath));
let methodName = camelToKebab(method);
let wanted = normalizeSdkPath(entry.methodResources?.[methodName] ?? defaultResource);
if (resource !== wanted) return false;
if (!entry.include?.length) return true;
return entry.include.some(name => camelToKebab(name) === camelToKebab(method));
return entry.include.some(name => camelToKebab(name) === methodName);
});

if (matches.length === 0) {
Expand Down
1 change: 1 addition & 0 deletions generator/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type CommandEntry = {
resource?: string;
group?: boolean;
include?: string[];
methodResources?: Record<string, string>;
aliases?: string[];
short?: string;
long?: string;
Expand Down
5 changes: 5 additions & 0 deletions internal/cli/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
authcmd "github.com/metorial/cli/internal/commands/auth"
clicmd "github.com/metorial/cli/internal/commands/cli"
completioncmd "github.com/metorial/cli/internal/commands/completion"
consumercmd "github.com/metorial/cli/internal/commands/consumer"
examplecmd "github.com/metorial/cli/internal/commands/example"
fetchcmd "github.com/metorial/cli/internal/commands/fetch"
filescmd "github.com/metorial/cli/internal/commands/files"
Expand All @@ -16,6 +17,7 @@ import (
systemcmd "github.com/metorial/cli/internal/commands/system"
"github.com/metorial/cli/internal/commandutil"
"github.com/metorial/cli/internal/config"
"github.com/metorial/cli/internal/resourcecmd"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -57,6 +59,9 @@ func newAdminRoot(application *app.App) (*cobra.Command, error) {
return nil, err
}
if !commandutil.BrowserShellEnabled() {
if integrations := resourcecmd.CommandByName(command, "integrations"); integrations != nil {
integrations.AddCommand(consumercmd.NewMemberCommand(ctx))
}
if err := filescmd.Attach(command, ctx); err != nil {
return nil, err
}
Expand Down
143 changes: 143 additions & 0 deletions internal/cli/admin_cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@ package cli

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/metorial/cli/internal/app"
"github.com/metorial/cli/internal/config"
"github.com/modelcontextprotocol/go-sdk/mcp"
)

func executeAdmin(t *testing.T, args ...string) (string, error) {
Expand Down Expand Up @@ -167,3 +173,140 @@ func TestAdminCLIProfileHintsUseAdminPath(t *testing.T) {
t.Fatalf("list output missing admin hint: %q", rendered)
}
}

func TestAdminProviderDiscoveryUsesCatalog(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("METORIAL_SKIP_UPDATE_CHECK", "1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/provider-listings" || r.URL.Query().Get("search") != "github" {
http.Error(w, "unexpected request", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"items":[{"id":"plg_1","provider":{"id":"pro_1"}}]}`)
}))
defer server.Close()

output, err := executeAdmin(t, "--api-host", server.URL, "--api-key", "metorial_sk_test",
"--format", "json", "providers", "list", "--search", "github")
var result struct {
Items []struct {
Provider struct{ ID string } `json:"provider"`
}
}
if err != nil || json.Unmarshal([]byte(output), &result) != nil ||
len(result.Items) != 1 || result.Items[0].Provider.ID != "pro_1" {
t.Fatalf("providers list = %q, %v", output, err)
}
}

func TestAdminIntegrationSetupResumesByID(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("METORIAL_SKIP_UPDATE_CHECK", "1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodPost && r.URL.Path == "/integration-setup-sessions":
_, _ = io.WriteString(w, `{"id":"iss_1","status":"pending","url":"https://example.test/setup"}`)
case r.Method == http.MethodGet && r.URL.Path == "/integration-setup-sessions/iss_1":
_, _ = io.WriteString(w, `{"id":"iss_1","status":"successful","integration_instance":{"id":"ini_1"}}`)
default:
http.Error(w, "unexpected request", http.StatusBadRequest)
}
}))
defer server.Close()

base := []string{"--api-host", server.URL, "--api-key", "metorial_sk_test", "--format", "json", "integrations", "setup"}
for _, step := range []struct {
args []string
status string
}{
{[]string{"--integration-id", "int_1", "--name", "GitHub", "--no-browser"}, "pending"},
{[]string{"status", "iss_1"}, "successful"},
{[]string{"wait", "iss_1", "--timeout", "1s"}, "successful"},
} {
output, err := executeAdmin(t, append(base, step.args...)...)
var result struct{ ID, Status string }
if err != nil || json.Unmarshal([]byte(output), &result) != nil || result.ID != "iss_1" || result.Status != step.status {
t.Fatalf("setup %v = %q, %v", step.args, output, err)
}
}
}

func TestAdminPersonalIntegrationReusesConsumerSetupAndMCP(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("METORIAL_SKIP_UPDATE_CHECK", "1")

protocol := mcp.NewServer(&mcp.Implementation{Name: "test", Version: "1"}, nil)
protocol.AddTool(&mcp.Tool{Name: "example", InputSchema: json.RawMessage(`{"type":"object"}`)},
func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
t.Error("verification must not call tools")
return nil, nil
})
mcpHandler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return protocol }, nil)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authorization := r.Header.Get("Authorization")
if r.URL.Path == "/member-consumer-session" {
if r.Method != http.MethodPost || authorization != "Bearer admin-token" ||
r.Header.Get("metorial-instance-id") != "ins_1" {
http.Error(w, "invalid exchange request", http.StatusUnauthorized)
return
}
var body struct {
IntegrationID string `json:"integration_id"`
}
if json.NewDecoder(r.Body).Decode(&body) != nil {
http.Error(w, "invalid exchange body", http.StatusBadRequest)
return
}
response := map[string]string{"access_token": "ephemeral-consumer-token"}
if body.IntegrationID == "int_1" {
response["catalog_item_id"] = "ptb_1"
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(response)
return
}

if authorization != "Bearer ephemeral-consumer-token" {
http.Error(w, "consumer credential required", http.StatusUnauthorized)
return
}
if r.URL.Path == "/connect/magic/example" {
mcpHandler.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
switch r.Method + " " + r.URL.Path {
case "GET /consumer/providers/ptb_1":
_, _ = io.WriteString(w, `{"id":"cat_1","type":"provider_template","availability":"available_now"}`)
case "POST /consumer/providers/cat_1/setup":
_, _ = io.WriteString(w, `{"id":"iss_1","status":"pending","url":"https://example.test/setup"}`)
case "GET /consumer/providers/cat_1/setup/iss_1":
_, _ = io.WriteString(w, `{"id":"iss_1","status":"successful"}`)
case "POST /consumer/providers/cat_1/deploy", "GET /magic-mcp-servers/mgsr_1":
_, _ = fmt.Fprintf(w, `{"id":"mgsr_1","endpoints":[{"url":"http://%s/connect/magic/example"}]}`, r.Host)
default:
http.Error(w, "unexpected endpoint", http.StatusNotFound)
}
}))
defer server.Close()

base := []string{"--api-host", server.URL, "--api-key", "admin-token", "--instance", "ins_1",
"--format", "json", "integrations", "personal"}
for _, step := range []struct {
args []string
want string
}{
{[]string{"setup", "int_1", "--no-browser"}, `"status": "pending"`},
{[]string{"status", "cat_1", "iss_1"}, `"status": "successful"`},
{[]string{"wait", "cat_1", "iss_1"}, `"status": "successful"`},
{[]string{"finish", "cat_1", "iss_1"}, `"tool_count": 1`},
{[]string{"tools", "mgsr_1"}, `"name": "example"`},
} {
output, err := executeAdmin(t, append(base, step.args...)...)
if err != nil || !strings.Contains(output, step.want) || strings.Contains(output, "ephemeral-consumer-token") {
t.Fatalf("personal %v = %q, %v", step.args, output, err)
}
}
}
7 changes: 6 additions & 1 deletion internal/commands/consumer/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import (
const defaultPageLimit = 15

type commandEnv struct {
ctx commandutil.Context
ctx commandutil.Context
member bool
}

func (e commandEnv) app() *app.App {
Expand All @@ -33,6 +34,10 @@ func (e commandEnv) client() (*consumerapi.Client, error) {
return nil, err
}

if e.member {
client, _, err := consumerapi.NewMember(runtime, "")
return client, err
}
return consumerapi.New(runtime)
}

Expand Down
30 changes: 24 additions & 6 deletions internal/commands/consumer/mcp_magic.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"

Expand All @@ -17,11 +18,11 @@ type magicMCPClient struct {
session *mcp.ClientSession
}

func connectMagicMCP(ctx context.Context, accessToken string, server *consumerapi.MagicMcpServer) (*magicMCPClient, error) {
func connectMagicMCP(ctx context.Context, clientAuth *consumerapi.Client, server *consumerapi.MagicMcpServer) (*magicMCPClient, error) {
if server == nil {
return nil, fmt.Errorf("metorial: integration is required")
}
if strings.TrimSpace(accessToken) == "" {
if clientAuth.AccessToken() == "" {
return nil, fmt.Errorf("metorial: an access token is required to connect to an integration")
}

Expand All @@ -43,8 +44,9 @@ func connectMagicMCP(ctx context.Context, accessToken string, server *consumerap
DisableStandaloneSSE: true,
HTTPClient: &http.Client{
Transport: &magicMCPAuthTransport{
base: http.DefaultTransport,
bearerToken: accessToken,
base: http.DefaultTransport,
bearerToken: clientAuth.AccessToken(),
allowedOrigin: clientAuth.MCPOrigin(),
},
},
}, nil)
Expand Down Expand Up @@ -151,11 +153,16 @@ func mcpContentToValues(contents []mcp.Content) []any {
}

type magicMCPAuthTransport struct {
base http.RoundTripper
bearerToken string
base http.RoundTripper
bearerToken string
allowedOrigin *url.URL
}

func (t *magicMCPAuthTransport) RoundTrip(request *http.Request) (*http.Response, error) {
if t.allowedOrigin != nil && !isTrustedMCPOrigin(t.allowedOrigin, request.URL) {
return nil, fmt.Errorf("metorial: integration endpoint is outside the configured API origin")
}

base := t.base
if base == nil {
base = http.DefaultTransport
Expand All @@ -172,3 +179,14 @@ func (t *magicMCPAuthTransport) RoundTrip(request *http.Request) (*http.Response

return base.RoundTrip(cloned)
}

func isTrustedMCPOrigin(api, endpoint *url.URL) bool {
if endpoint.User != nil || !strings.EqualFold(api.Scheme, endpoint.Scheme) {
return false
}
if strings.EqualFold(api.Host, endpoint.Host) {
return true
}
return api.Scheme == "https" && endpoint.Host == "api.metorial.com" &&
(api.Host == "api-us1.metorial.com" || api.Host == "api-eu1.metorial.com")
}
Loading
Loading