diff --git a/cmd/aws_devops_agent/plan_print_test.go b/cmd/aws_devops_agent/plan_print_test.go index eb1447d60..a3b5d1d43 100644 --- a/cmd/aws_devops_agent/plan_print_test.go +++ b/cmd/aws_devops_agent/plan_print_test.go @@ -84,7 +84,7 @@ func TestTokenPromptAsksWhenInteractive(t *testing.T) { assert.Contains(t, w.calls, "RegisterService") assert.Less(t, strings.Index(stderrOf(cmd), "Paste the token"), strings.Index(stderrOf(cmd), "Setup plan:")) // The plan is built again with the token, so it is current. - assert.Contains(t, stderrOf(cmd), "Register MCP server LaunchDarkly at") + assert.Contains(t, stderrOf(cmd), "Register a new MCP server for this agent space at") assert.NotContains(t, stderrOf(cmd), "Ask for a token") } @@ -178,12 +178,13 @@ func TestSetupNeedsATokenItCannotAsk(t *testing.T) { } } -// A registered server needs no token. +// The server of the agent space needs no token. func TestSetupWithoutTokenReusesServer(t *testing.T) { cmd, _ := setupTestCmd(t, "") cmd.SetIn(noReadStdin{t}) - clients, w := countingClients() + clients, w := countingClients(agenttypes.AgentSpace{AgentSpaceId: aws.String("space-1"), Name: aws.String("platform")}) agent := clients.Agent.(countingAgent) + agent.associations = []agenttypes.Association{{AssociationId: aws.String("assoc-1"), ServiceId: aws.String("mcp-1")}} agent.services = []agenttypes.RegisteredService{{ ServiceId: aws.String("mcp-1"), ServiceType: agenttypes.ServiceMcpServer, @@ -193,10 +194,12 @@ func TestSetupWithoutTokenReusesServer(t *testing.T) { }} clients.Agent = agent - require.NoError(t, setupWith(cmd, clients, noTokenOptions(), true, false)) + opts := noTokenOptions() + opts.AgentSpaceName, opts.AgentSpaceID = "", "space-1" + + require.NoError(t, setupWith(cmd, clients, opts, true, false)) assert.NotContains(t, w.calls, "RegisterService") - assert.Contains(t, w.calls, "AssociateService") } func TestSetupPlanNamesAccountAssociation(t *testing.T) { @@ -429,12 +432,13 @@ func TestSetupFailureNamesTheNewSpace(t *testing.T) { assert.Contains(t, err.Error(), "To use it, run setup again with --agent-space-id space-new") } -// A server that appears between the two plans is reused, and setup says -// that it does not use the pasted token. +// A server that the space gets between the two plans is reused, and setup +// says that it does not use the pasted token. func TestSetupSaysWhenTheSecondPlanReusesAServer(t *testing.T) { cmd, _ := setupTestCmd(t, "api-token\n") - clients, _ := countingClients() + clients, _ := countingClients(agenttypes.AgentSpace{AgentSpaceId: aws.String("space-1"), Name: aws.String("platform")}) agent := clients.Agent.(countingAgent) + agent.associations = []agenttypes.Association{{AssociationId: aws.String("assoc-7"), ServiceId: aws.String("mcp-7")}} agent.services = []agenttypes.RegisteredService{{ ServiceId: aws.String("mcp-7"), ServiceType: agenttypes.ServiceMcpServer, @@ -444,6 +448,7 @@ func TestSetupSaysWhenTheSecondPlanReusesAServer(t *testing.T) { }} clients.Agent = agent opts := noTokenOptions() + opts.AgentSpaceName, opts.AgentSpaceID = "", "space-1" first := awsdevops.SetupPlan{MCP: awsdevops.MCPStep{Action: awsdevops.MCPAsk}} plan, err := planWithToken(cmd, clients, &opts, first, true) diff --git a/cmd/aws_devops_agent/select_test.go b/cmd/aws_devops_agent/select_test.go index 054f46868..fda78c70a 100644 --- a/cmd/aws_devops_agent/select_test.go +++ b/cmd/aws_devops_agent/select_test.go @@ -20,6 +20,8 @@ import ( type stubAgent struct { spaces []agenttypes.AgentSpace services []agenttypes.RegisteredService + // associations are the associations of every space. + associations []agenttypes.Association // unreadTags fails the tag lookup of these space IDs. unreadTags map[string]bool // missing makes GetAgentSpace report these space IDs as not found. @@ -88,7 +90,7 @@ func (s stubAgent) ListAgentSpaces(context.Context, *devopsagent.ListAgentSpaces } func (s stubAgent) ListAssociations(context.Context, *devopsagent.ListAssociationsInput, ...func(*devopsagent.Options)) (*devopsagent.ListAssociationsOutput, error) { - return &devopsagent.ListAssociationsOutput{}, nil + return &devopsagent.ListAssociationsOutput{Associations: s.associations}, nil } func (s stubAgent) ListServices(context.Context, *devopsagent.ListServicesInput, ...func(*devopsagent.Options)) (*devopsagent.ListServicesOutput, error) { diff --git a/cmd/aws_devops_agent/setup.go b/cmd/aws_devops_agent/setup.go index ecda41d58..9efa8acfc 100644 --- a/cmd/aws_devops_agent/setup.go +++ b/cmd/aws_devops_agent/setup.go @@ -46,11 +46,13 @@ full setup. Pass --agent-space-id to pick a space without the list, or --agent-space-name, or type one when setup asks. The run ends with the operator app URL, where the agent is used. -The MCP server is connected with --access-token, or with the token in your -ldcli configuration when you do not pass one. AWS keeps the token and the agent -acts as its account and role, so a session token from 'ldcli login' stops -working once it expires. With no token, setup reuses a registered MCP server. -If none exists, setup asks for a service token in a terminal and checks it +Each agent space gets its own LaunchDarkly MCP server registration, so each +space can use a different token. The MCP server is connected with +--access-token, or with the token in your ldcli configuration when you do not +pass one. AWS keeps the token and the agent acts as its account and role, so a +session token from 'ldcli login' stops working once it expires. If the agent +space already has an MCP server, setup reuses it and does not change its token. +If it has none, setup asks for a service token in a terminal and checks it before it changes AWS. Without a terminal, or with --yes, it stops and asks for --access-token.`, Args: cobra.NoArgs, @@ -69,9 +71,9 @@ for --access-token.`, cmd.Flags().String(issuerURLFlag, "", "OIDC issuer URL, required when --auth-flow=idp") cmd.Flags().String(idpClientIDFlag, "", "OIDC client ID, required when --auth-flow=idp") cmd.Flags().String(idpClientSecretFlag, "", "OIDC client secret, required when --auth-flow=idp") - cmd.Flags().Bool(replaceMCPTokenFlag, false, "Re-register the LaunchDarkly MCP server so it uses the token passed with --access-token") - cmd.Flags().String(mcpServiceIDFlag, "", "Registered MCP server to use, instead of the one registered at --mcp-endpoint") - cmd.Flags().String(mcpEndpointFlag, "", "MCP endpoint to register and look the server up by. Defaults to "+awsdevops.MCPServerEndpoint) + cmd.Flags().Bool(replaceMCPTokenFlag, false, "Give the agent space a new LaunchDarkly MCP server with the token passed with --access-token. Other agent spaces keep their server") + cmd.Flags().String(mcpServiceIDFlag, "", "Registered MCP server to connect, instead of the server of the agent space") + cmd.Flags().String(mcpEndpointFlag, "", "MCP endpoint to register. Setup reuses only a server at this endpoint. Defaults to "+awsdevops.MCPServerEndpoint) cmd.Flags().Bool(yesFlag, false, "Ask no questions and accept every step") diff --git a/internal/awsdevops/awsdevops_test.go b/internal/awsdevops/awsdevops_test.go index e548dfd93..7dd86a549 100644 --- a/internal/awsdevops/awsdevops_test.go +++ b/internal/awsdevops/awsdevops_test.go @@ -50,6 +50,9 @@ type fakeAgent struct { registerOutput *devopsagent.RegisterServiceOutput registerErr error deregisterErr error + disassociateErr error + // onDisassociate runs before DisassociateService returns. + onDisassociate func() registerInputs []*devopsagent.RegisterServiceInput associations []agenttypes.Association agentSpaces []agenttypes.AgentSpace @@ -123,6 +126,12 @@ func (f *fakeAgent) DeregisterService(_ context.Context, in *devopsagent.Deregis func (f *fakeAgent) DisassociateService(_ context.Context, in *devopsagent.DisassociateServiceInput, _ ...func(*devopsagent.Options)) (*devopsagent.DisassociateServiceOutput, error) { f.calls = append(f.calls, "DisassociateService") + if f.onDisassociate != nil { + f.onDisassociate() + } + if f.disassociateErr != nil { + return nil, f.disassociateErr + } f.disassociatedIDs = append(f.disassociatedIDs, aws.ToString(in.AssociationId)) return &devopsagent.DisassociateServiceOutput{}, nil @@ -363,8 +372,9 @@ func TestSetupCreatesRolesAgentSpaceAndAssociations(t *testing.T) { assert.Contains(t, iamClient.inlinePolicies[awsdevops.AgentSpaceRoleName], "iam:CreateServiceLinkedRole") assert.Equal( t, - // Plan lookup, the pre-write check, and the check before the MCP step. - []string{"ListServices", "ListServices", "CreateAgentSpace", "AssociateService", "EnableOperatorApp", "ListServices", "RegisterService", "AssociateService"}, + // The plan does not look for the server of a new space. The check + // before the MCP step looks, because the space exists by then. + []string{"CreateAgentSpace", "AssociateService", "EnableOperatorApp", "ListServices", "RegisterService", "AssociateService"}, agent.calls, ) } @@ -501,12 +511,13 @@ func stubLaunchDarkly(t *testing.T, status int) string { func TestSetupReusesAnExistingMCPServerWithoutAToken(t *testing.T) { agent := &fakeAgent{ - services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-existing")}, + services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-existing")}, + associations: mcpLink("mcp-existing"), } result, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ - AgentSpaceName: "launchdarkly", - AuthFlow: "iam", + AgentSpaceID: "space-1", + AuthFlow: "iam", }) require.NoError(t, err) @@ -538,7 +549,7 @@ func TestSetupDisassociatesTheMCPServerBeforeReplacingItsToken(t *testing.T) { } result, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ - AgentSpaceName: "launchdarkly", + AgentSpaceID: "space-1", AuthFlow: "iam", LDBaseURI: stubLaunchDarkly(t, http.StatusOK), LDAccessToken: "api-token", @@ -553,37 +564,6 @@ func TestSetupDisassociatesTheMCPServerBeforeReplacingItsToken(t *testing.T) { assert.Equal(t, "assoc-mcp-1", result.MCPAssociationID) } -func TestSetupReconnectsOtherSpacesAfterReplacingTheMCPToken(t *testing.T) { - agent := &fakeAgent{ - agentSpaces: []agenttypes.AgentSpace{ - {AgentSpaceId: aws.String("space-1")}, - {AgentSpaceId: aws.String("space-2")}, - }, - services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-existing")}, - associations: []agenttypes.Association{{ - AssociationId: aws.String("assoc-mcp-existing"), - ServiceId: aws.String("mcp-existing"), - }}, - } - - _, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ - AgentSpaceID: "space-1", - AuthFlow: "iam", - LDBaseURI: stubLaunchDarkly(t, http.StatusOK), - LDAccessToken: "api-token", - ReplaceMCPToken: true, - }) - require.NoError(t, err) - - associated := []string{} - for _, in := range agent.associationInputs { - if aws.ToString(in.ServiceId) == "mcp-1" { - associated = append(associated, aws.ToString(in.AgentSpaceId)) - } - } - assert.Equal(t, []string{"space-1", "space-2"}, associated) -} - func TestSetupKeepsTheMCPServerWhenLaunchDarklyRejectsTheNewToken(t *testing.T) { agent := &fakeAgent{ services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-existing")}, @@ -607,14 +587,10 @@ func TestSetupKeepsTheMCPServerWhenLaunchDarklyRejectsTheNewToken(t *testing.T) assert.NotContains(t, agent.calls, "RegisterService") } -func TestSetupNamesTheSpacesLeftWithoutAnMCPServer(t *testing.T) { +func TestSetupNamesTheSpaceLeftWithoutAnMCPServer(t *testing.T) { agent := &fakeAgent{ registerErr: errors.New("ValidationException: something broke"), - agentSpaces: []agenttypes.AgentSpace{ - {AgentSpaceId: aws.String("space-1")}, - {AgentSpaceId: aws.String("space-2")}, - }, - services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-existing")}, + services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-existing")}, associations: []agenttypes.Association{{ AssociationId: aws.String("assoc-mcp-existing"), ServiceId: aws.String("mcp-existing"), @@ -629,7 +605,7 @@ func TestSetupNamesTheSpacesLeftWithoutAnMCPServer(t *testing.T) { ReplaceMCPToken: true, }) - assert.ErrorContains(t, err, "agent spaces space-1, space-2 have no LaunchDarkly MCP server") + assert.ErrorContains(t, err, "agent spaces space-1 have no LaunchDarkly MCP server") assert.ErrorContains(t, err, "--access-token") } diff --git a/internal/awsdevops/lookup.go b/internal/awsdevops/lookup.go index 544db3180..444d41e46 100644 --- a/internal/awsdevops/lookup.go +++ b/internal/awsdevops/lookup.go @@ -197,29 +197,66 @@ func agentSpaceARN(region, accountID, spaceID string) string { return fmt.Sprintf("arn:aws:aidevops:%s:%s:agentspace/%s", region, accountID, spaceID) } -// FindMCPServer returns the ID of the MCP server registered at endpoint, if the -// account has one. AWS keeps MCP servers at the account level, so a second -// agent space reuses the existing registration. -func FindMCPServer(ctx context.Context, clients Clients, endpoint string) (string, error) { - id, _, err := findMCPService(ctx, clients, endpoint) +// MCPServerNameFor is the name of the MCP server that setup registers for an +// agent space. AWS needs a unique name of letters, digits, "_" and "-", and +// the ID ties the server to the space. +func MCPServerNameFor(agentSpaceID string) string { + return MCPServerName + "-" + agentSpaceID +} - return id, err +// mcpRef identifies a registered MCP server. +type mcpRef struct { + ID string + Name string } -// findMCPService returns the ID and the name of the MCP server registered at -// endpoint, if the account has one. -func findMCPService(ctx context.Context, clients Clients, endpoint string) (id, name string, err error) { +// spaceMCPServers finds the LaunchDarkly MCP servers at endpoint of an agent +// space. linked is the server that the space is connected to. own is the +// server with the name that setup gives the space, which can be the same +// server. AWS keeps MCP servers at the account level, and each one has the +// token of one LaunchDarkly account, so the server of another space is never +// a match. A space connected to more than one server is an error, because +// setup cannot tell which one to use. +func spaceMCPServers(ctx context.Context, clients Clients, agentSpaceID, endpoint string) (linked, own mcpRef, err error) { + // A new space has no ID and no server yet. + if agentSpaceID == "" { + return mcpRef{}, mcpRef{}, nil + } + associations, err := listAssociations(ctx, clients, agentSpaceID) + if err != nil { + return mcpRef{}, mcpRef{}, err + } + links := make(map[string]bool, len(associations)) + for _, association := range associations { + links[aws.ToString(association.ServiceId)] = true + } services, err := listServices(ctx, clients) if err != nil { - return "", "", err + return mcpRef{}, mcpRef{}, err } + var all []string for _, service := range services { - if mcpEndpointOf(service) == endpoint { - return aws.ToString(service.ServiceId), serviceName(service), nil + if mcpEndpointOf(service) != endpoint { + continue + } + ref := mcpRef{ID: aws.ToString(service.ServiceId), Name: serviceName(service)} + if links[ref.ID] { + linked = ref + all = append(all, fmt.Sprintf("%s (%s)", ref.Name, ref.ID)) } + if own.ID == "" && ref.Name == MCPServerNameFor(agentSpaceID) { + own = ref + } + } + if len(all) > 1 { + return mcpRef{}, mcpRef{}, fmt.Errorf( + "agent space %s is connected to %d LaunchDarkly MCP servers: %s. "+ + "Disconnect all but one in the AWS console, then run setup again", + agentSpaceID, len(all), strings.Join(all, ", "), + ) } - return "", "", nil + return linked, own, nil } // spacesNamed lists IDs of spaces named name. diff --git a/internal/awsdevops/lookup_test.go b/internal/awsdevops/lookup_test.go index ca810495e..bded76370 100644 --- a/internal/awsdevops/lookup_test.go +++ b/internal/awsdevops/lookup_test.go @@ -15,15 +15,16 @@ import ( "github.com/launchdarkly/ldcli/internal/awsdevops" ) -func TestSetupReusesAnAlreadyRegisteredMCPServer(t *testing.T) { +func TestSetupReusesTheMCPServerOfTheAgentSpace(t *testing.T) { agent := &fakeAgent{ - services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-1")}, + services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-1")}, + spaceLinks: map[string][]agenttypes.Association{"space-1": mcpLink("mcp-1")}, } result, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ - AgentSpaceName: "launchdarkly", - AuthFlow: "iam", - LDAccessToken: "api-token", + AgentSpaceID: "space-1", + AuthFlow: "iam", + LDAccessToken: "api-token", }) require.NoError(t, err) @@ -32,13 +33,58 @@ func TestSetupReusesAnAlreadyRegisteredMCPServer(t *testing.T) { assert.Equal(t, "assoc-mcp-1", result.MCPAssociationID) } +// The server of another space has the token of that space, so a space never +// uses it. +func TestSetupRegistersAServerBesideTheServerOfAnotherSpace(t *testing.T) { + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{{AgentSpaceId: aws.String("space-1")}, {AgentSpaceId: aws.String("space-2")}}, + services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-other")}, + spaceLinks: map[string][]agenttypes.Association{"space-2": mcpLink("mcp-other")}, + } + + result, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ + AgentSpaceID: "space-1", + AuthFlow: "iam", + LDAccessToken: "api-token", + }) + require.NoError(t, err) + + assert.Equal(t, "mcp-1", result.MCPServiceID) + require.Len(t, agent.registerInputs, 1) + details, ok := agent.registerInputs[0].ServiceDetails.(*agenttypes.ServiceDetailsMemberMcpserver) + require.True(t, ok) + assert.Equal(t, awsdevops.MCPServerNameFor("space-1"), aws.ToString(details.Value.Name)) + assert.Empty(t, agent.disassociatedIDs) +} + +// A run that registered the server and failed to connect it leaves a server +// with the name of the space. The next run connects that server. +func TestSetupReusesTheServerItRegisteredForTheSpace(t *testing.T) { + agent := &fakeAgent{ + services: []agenttypes.RegisteredService{ + mcpService("mcp-other", awsdevops.MCPServerNameFor("space-2"), awsdevops.MCPServerEndpoint), + mcpService("mcp-own", awsdevops.MCPServerNameFor("space-1"), awsdevops.MCPServerEndpoint), + }, + } + + result, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ + AgentSpaceID: "space-1", + AuthFlow: "iam", + }) + require.NoError(t, err) + + assert.NotContains(t, agent.calls, "RegisterService") + assert.Equal(t, "mcp-own", result.MCPServiceID) +} + func TestSetupReplacesTheMCPServerTokenWhenAsked(t *testing.T) { agent := &fakeAgent{ - services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-1")}, + services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-old")}, + spaceLinks: map[string][]agenttypes.Association{"space-1": mcpLink("mcp-old")}, } result, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ - AgentSpaceName: "launchdarkly", + AgentSpaceID: "space-1", AuthFlow: "iam", LDBaseURI: stubLaunchDarkly(t, http.StatusOK), LDAccessToken: "api-token", @@ -46,34 +92,34 @@ func TestSetupReplacesTheMCPServerTokenWhenAsked(t *testing.T) { }) require.NoError(t, err) - assert.Equal(t, []string{"mcp-1"}, agent.deregisteredIDs) - assert.Contains(t, agent.calls, "RegisterService") + assert.Equal(t, []string{"mcp-old"}, agent.deregisteredIDs) assert.Equal(t, "mcp-1", result.MCPServiceID) } -func TestFindMCPServerMatchesOnTheEndpointInTheServiceDetails(t *testing.T) { - agent := &fakeAgent{ - services: []agenttypes.RegisteredService{ - { - ServiceId: aws.String("mcp-2"), - ServiceType: agenttypes.ServiceMcpServer, - AdditionalServiceDetails: &agenttypes.AdditionalServiceDetailsMemberMcpserver{ - Value: agenttypes.RegisteredMCPServerDetails{ - Endpoint: aws.String(awsdevops.MCPServerEndpoint), - }, - }, - }, - }, - } +// A replacement on a shared server changes only this space. The other spaces +// keep the server and its token. +func TestSetupReplaceLeavesASharedServerToTheOtherSpaces(t *testing.T) { + agent := replaceAcrossSpaces() - serviceID, err := awsdevops.FindMCPServer( - context.Background(), - newTestClients(agent, newFakeIAM()), - awsdevops.MCPServerEndpoint, - ) + result, err := awsdevops.Setup(context.Background(), newTestClients(agent, newFakeIAM()), awsdevops.SetupOptions{ + AgentSpaceID: "space-1", + AuthFlow: "iam", + LDBaseURI: stubLaunchDarkly(t, http.StatusOK), + LDAccessToken: "api-token", + ReplaceMCPToken: true, + }) require.NoError(t, err) - assert.Equal(t, "mcp-2", serviceID) + assert.Empty(t, agent.deregisteredIDs) + assert.Equal(t, []string{"assoc-mcp-old"}, agent.disassociatedIDs) + assert.Equal(t, "mcp-1", result.MCPServiceID) + var associated []string + for _, in := range agent.associationInputs { + if aws.ToString(in.ServiceId) == "mcp-1" { + associated = append(associated, aws.ToString(in.AgentSpaceId)) + } + } + assert.Equal(t, []string{"space-1"}, associated) } const space1ARN = "arn:aws:aidevops:us-east-1:" + testAccountID + ":agentspace/space-1" diff --git a/internal/awsdevops/plan_test.go b/internal/awsdevops/plan_test.go index 643218686..93486f3c1 100644 --- a/internal/awsdevops/plan_test.go +++ b/internal/awsdevops/plan_test.go @@ -272,7 +272,7 @@ func TestPlanTextOfAConnectPlan(t *testing.T) { assert.Equal(t, "No change", text.Association) assert.Equal(t, []string{"No change"}, text.Roles) assert.Equal(t, tc.want, text.OperatorApp) - assert.Equal(t, "Register MCP server "+awsdevops.MCPServerName+" at "+awsdevops.MCPServerEndpoint, text.MCPServer) + assert.Equal(t, "Register a new MCP server for this agent space at "+awsdevops.MCPServerEndpoint, text.MCPServer) }) } } @@ -285,11 +285,13 @@ func TestPlanTextOfASkippedMCPServer(t *testing.T) { // The plan names the server by its name in AWS, which the customer can change. func TestPlanNamesTheReusedMCPServerByItsName(t *testing.T) { - for name, id := range map[string]string{"found by endpoint": "", "given by ID": "mcp-1"} { + for name, id := range map[string]string{"connected to the space": "", "given by ID": "mcp-1"} { t.Run(name, func(t *testing.T) { - agent := &fakeAgent{services: []agenttypes.RegisteredService{ - mcpService("mcp-1", "LaunchDarkly (prod)", awsdevops.MCPServerEndpoint), - }} + agent := &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "launchdarkly")}, + services: []agenttypes.RegisteredService{mcpService("mcp-1", "LaunchDarkly (prod)", awsdevops.MCPServerEndpoint)}, + associations: mcpLink("mcp-1"), + } opts := runPlanOptions() opts.MCPServiceID = id @@ -323,7 +325,7 @@ func TestPlanConnectWithoutANameAsksForTheID(t *testing.T) { assert.EqualError(t, err, "no agent space to connect to. Pass --agent-space-id") } -// The replace plan names touched spaces. +// A replace plan on a shared server names the spaces that keep it. func TestPlanReplaceNamesEachSpace(t *testing.T) { opts := runPlanOptions() opts.ReplaceMCPToken = true @@ -331,9 +333,10 @@ func TestPlanReplaceNamesEachSpace(t *testing.T) { plan, err := awsdevops.PlanSetup(context.Background(), newTestClients(replaceAcrossSpaces(), newFakeIAM()), opts, true) require.NoError(t, err) - assert.Contains(t, plan.Text().MCPServer, "space-1") - assert.Contains(t, plan.Text().MCPServer, "space-3") - assert.NotContains(t, plan.Text().MCPServer, "space-2") + assert.Equal(t, + "Register a new MCP server for this agent space at "+awsdevops.MCPServerEndpoint+ + ". MCP server LaunchDarkly (mcp-old) keeps its token for space-3", + plan.Text().MCPServer) } // Two spaces with one name leave no safe choice. @@ -454,6 +457,14 @@ func replaceAcrossSpaces() *fakeAgent { } } +// replaceOnOneSpace is replaceAcrossSpaces with mcp-old on space-1 only. +func replaceOnOneSpace() *fakeAgent { + agent := replaceAcrossSpaces() + agent.spaceLinks = map[string][]agenttypes.Association{"space-1": mcpLink("mcp-old")} + + return agent +} + func mcpLink(serviceID string) []agenttypes.Association { return []agenttypes.Association{{AssociationId: aws.String("assoc-" + serviceID), ServiceId: aws.String(serviceID)}} } diff --git a/internal/awsdevops/runplan_test.go b/internal/awsdevops/runplan_test.go index 95c0d87a4..5bd351dda 100644 --- a/internal/awsdevops/runplan_test.go +++ b/internal/awsdevops/runplan_test.go @@ -668,7 +668,7 @@ func TestConnectPlanUsesTheURLThatAWSReturns(t *testing.T) { func TestRunPlanStopsWhenReusedMCPServerIsGone(t *testing.T) { for name, replace := range map[string]bool{"reuse": false, "replace": true} { t.Run(name, func(t *testing.T) { - agent := &fakeAgent{services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-old")}} + agent := linkedSpace("mcp-old") iamClient := newFakeIAM() clients := newTestClients(agent, iamClient) opts := runPlanOptions() @@ -690,8 +690,11 @@ func TestRunPlanStopsWhenReusedMCPServerIsGone(t *testing.T) { func TestRunPlanStopsWhenMCPServerAppears(t *testing.T) { agent, iamClient := &fakeAgent{}, newFakeIAM() + agent.agentSpaces = []agenttypes.AgentSpace{namedSpace("space-1", "launchdarkly")} + err := planThenRun(t, agent, iamClient, func() { agent.services = []agenttypes.RegisteredService{launchDarklyMCPService("mcp-new")} + agent.associations = mcpLink("mcp-new") }) require.ErrorIs(t, err, awsdevops.ErrPlanChanged) @@ -701,7 +704,7 @@ func TestRunPlanStopsWhenMCPServerAppears(t *testing.T) { // Setup uses the planned server ID. func TestRunPlanKeepsThePlannedMCPServer(t *testing.T) { - agent := &fakeAgent{services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-old")}} + agent := linkedSpace("mcp-old") clients := newTestClients(agent, newFakeIAM()) plan, err := awsdevops.PlanSetup(context.Background(), clients, runPlanOptions(), true) require.NoError(t, err) @@ -724,6 +727,7 @@ func TestRegisterMCPServerStopsWhenServerAppears(t *testing.T) { result, err := awsdevops.RunPlan(context.Background(), clients, opts, plan) require.NoError(t, err) agent.services = []agenttypes.RegisteredService{launchDarklyMCPService("mcp-someone")} + agent.associations = mcpLink("mcp-someone") opts.LDAccessToken, opts.ReplaceMCPToken = "pasted-token", true err = awsdevops.RegisterMCPServer(context.Background(), clients, opts, plan.MCP, &result) @@ -757,6 +761,7 @@ func TestConnectPlanStopsWhenServerAppears(t *testing.T) { plan, err := awsdevops.PlanSetup(context.Background(), clients, opts, false) require.NoError(t, err) agent.services = []agenttypes.RegisteredService{launchDarklyMCPService("mcp-someone")} + agent.associations = mcpLink("mcp-someone") _, err = awsdevops.ConnectPlan(context.Background(), clients, opts, plan) @@ -838,7 +843,7 @@ func TestRunPlanChecksTokenBeforeWrites(t *testing.T) { } func TestRunPlanChecksReplaceTokenBeforeWrites(t *testing.T) { - agent := &fakeAgent{services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-old")}} + agent := linkedSpace("mcp-old") iamClient := newFakeIAM() clients := newTestClients(agent, iamClient) opts := rejectingOptions(t, http.StatusUnauthorized) @@ -854,7 +859,7 @@ func TestRunPlanChecksReplaceTokenBeforeWrites(t *testing.T) { // A reused server keeps its token. func TestRunPlanSkipsTokenItWillNotSend(t *testing.T) { - agent := &fakeAgent{services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-old")}} + agent := linkedSpace("mcp-old") clients := newTestClients(agent, newFakeIAM()) opts := runPlanOptions() opts.LDBaseURI = "http://127.0.0.1:1" @@ -960,6 +965,7 @@ func TestRunPlanStopsWhenMCPServerAppearsDuringRoleWrites(t *testing.T) { require.Equal(t, awsdevops.MCPRegister, plan.MCP.Action) iamClient.onCreateRole = func(string) { agent.services = []agenttypes.RegisteredService{launchDarklyMCPService("mcp-new")} + agent.associations = mcpLink("mcp-new") } _, err = awsdevops.RunPlan(context.Background(), clients, runPlanOptions(), plan) @@ -971,8 +977,9 @@ func TestRunPlanStopsWhenMCPServerAppearsDuringRoleWrites(t *testing.T) { // A reused server that goes during the role writes stops the run. func TestRunPlanStopsWhenReusedMCPServerGoesDuringRoleWrites(t *testing.T) { agent := &fakeAgent{ - agentSpaces: []agenttypes.AgentSpace{namedSpace("space-7", "launchdarkly")}, - services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-1")}, + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-7", "launchdarkly")}, + services: []agenttypes.RegisteredService{launchDarklyMCPService("mcp-1")}, + associations: mcpLink("mcp-1"), } iamClient := newFakeIAM() clients := newTestClients(agent, iamClient) @@ -1002,37 +1009,50 @@ func replaceRun(t *testing.T, agent *fakeAgent) (awsdevops.SetupResult, error) { return awsdevops.RunPlan(context.Background(), clients, opts, plan) } -// The old server is gone when the name clash happens, so the error names -// each space that lost it. -func TestRunPlanReplaceNameClashNamesTheDisconnectedSpaces(t *testing.T) { +// A failed registration on a shared server changes nothing, because the +// other spaces keep the old server and this space is still connected to it. +func TestRunPlanReplaceNameClashKeepsTheSharedServer(t *testing.T) { agent := replaceAcrossSpaces() agent.registerErr = errors.New("ConflictException: a service named LaunchDarkly already exists") _, err := replaceRun(t, agent) require.Error(t, err) - assert.ErrorContains(t, err, "Rename that server in the AWS console") - assert.ErrorContains(t, err, "agent spaces space-1, space-3 have no LaunchDarkly MCP server") + assert.ErrorContains(t, err, "rename it in the AWS console") + assert.NotContains(t, err.Error(), "have no LaunchDarkly MCP server") + assert.Empty(t, agent.disassociatedIDs) + assert.Empty(t, agent.deregisteredIDs) +} + +// The server of only this space is gone when the name clash happens, so the +// error names the space. +func TestRunPlanReplaceNameClashNamesTheDisconnectedSpace(t *testing.T) { + agent := replaceOnOneSpace() + agent.registerErr = errors.New("ConflictException: a service named LaunchDarkly already exists") + + _, err := replaceRun(t, agent) + + require.Error(t, err) + assert.ErrorContains(t, err, "rename it in the AWS console") + assert.ErrorContains(t, err, "agent spaces space-1 have no LaunchDarkly MCP server") assert.ErrorContains(t, err, "--agent-space-id ") - assert.NotContains(t, err.Error(), "--mcp-service-id") } -func TestRunPlanReplaceFailedDeregisterNamesTheDisconnectedSpaces(t *testing.T) { - agent := replaceAcrossSpaces() +func TestRunPlanReplaceFailedDeregisterNamesTheDisconnectedSpace(t *testing.T) { + agent := replaceOnOneSpace() agent.deregisterErr = errors.New("InternalServerException") _, err := replaceRun(t, agent) require.Error(t, err) assert.ErrorContains(t, err, "unable to deregister the existing LaunchDarkly MCP server mcp-old") - assert.ErrorContains(t, err, "Agent spaces space-1, space-3 are already disconnected from it") + assert.ErrorContains(t, err, "Agent spaces space-1 are already disconnected from it") assert.ErrorContains(t, err, "--agent-space-id ") assert.NotContains(t, agent.calls, "RegisterService") } -// The plan names the server by its name in AWS, so the new registration -// keeps that name. -func TestRunPlanReplaceKeepsTheServerName(t *testing.T) { +// The new server has the name of its space, which AWS needs to be unique. +func TestRunPlanReplaceNamesTheServerForTheSpace(t *testing.T) { agent := replaceAcrossSpaces() agent.services = []agenttypes.RegisteredService{mcpService("mcp-old", "Prod LD", awsdevops.MCPServerEndpoint)} @@ -1042,7 +1062,7 @@ func TestRunPlanReplaceKeepsTheServerName(t *testing.T) { require.Len(t, agent.registerInputs, 1) details, ok := agent.registerInputs[0].ServiceDetails.(*agenttypes.ServiceDetailsMemberMcpserver) require.True(t, ok) - assert.Equal(t, "Prod LD", aws.ToString(details.Value.Name)) + assert.Equal(t, awsdevops.MCPServerNameFor("space-1"), aws.ToString(details.Value.Name)) } // A link added during writes stops replace. @@ -1089,8 +1109,8 @@ func runReplace(t *testing.T, agent *fakeAgent) error { return err } -// The other spaces get the new server even if this space fails. -func TestReplaceReconnectsOtherSpacesWhenThisOneFails(t *testing.T) { +// A failure on this space does not touch the other spaces. +func TestReplaceLeavesTheOtherSpacesAloneWhenThisOneFails(t *testing.T) { agent := replaceAcrossSpaces() agent.failAssociateFor = map[string]bool{"space-1": true} @@ -1098,24 +1118,10 @@ func TestReplaceReconnectsOtherSpacesWhenThisOneFails(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "agent space space-1") - assert.NotContains(t, err.Error(), "lost the LaunchDarkly MCP server") - var reconnected []string + assert.Empty(t, agent.deregisteredIDs) for _, in := range agent.associationInputs { - reconnected = append(reconnected, aws.ToString(in.AgentSpaceId)) + assert.NotEqual(t, "space-3", aws.ToString(in.AgentSpaceId)) } - assert.Contains(t, reconnected, "space-3") -} - -// A failed reconnect names the space, so the user can fix it. -func TestReplaceNamesASpaceThatLostTheServer(t *testing.T) { - agent := replaceAcrossSpaces() - agent.failAssociateFor = map[string]bool{"space-3": true} - - err := runReplace(t, agent) - - require.Error(t, err) - assert.Contains(t, err.Error(), "agent spaces space-3 lost the LaunchDarkly MCP server") - assert.Contains(t, err.Error(), "--agent-space-id") } // The role step can take minutes, so the app step checks the app again. @@ -1150,3 +1156,208 @@ func TestRunPlanStopsWhenAppTurnsOffDuringRoles(t *testing.T) { require.ErrorIs(t, err, awsdevops.ErrPlanChanged) assert.Contains(t, err.Error(), "disabled after the plan") } + +// linkedSpace is the agent space space-1, named launchdarkly, connected to +// the LaunchDarkly MCP server serviceID. +func linkedSpace(serviceID string) *fakeAgent { + return &fakeAgent{ + agentSpaces: []agenttypes.AgentSpace{namedSpace("space-1", "launchdarkly")}, + services: []agenttypes.RegisteredService{launchDarklyMCPService(serviceID)}, + associations: mcpLink(serviceID), + } +} + +// A replace on a shared server registers the new server first. If the old +// server then cannot be disconnected, setup removes the new server, so the +// space stays as it was and a run again plans the same steps. +func TestReplaceRemovesTheNewServerWhenTheDisconnectFails(t *testing.T) { + agent := replaceAcrossSpaces() + agent.disassociateErr = errors.New("InternalServerException") + + result, err := replaceRun(t, agent) + + require.Error(t, err) + assert.ErrorContains(t, err, "unable to disconnect MCP server mcp-old from agent space space-1") + assert.ErrorContains(t, err, "still uses MCP server mcp-old with its old token") + assert.Equal(t, []string{"mcp-1"}, agent.deregisteredIDs) + assert.Empty(t, result.MCPServiceID) +} + +// If the new server cannot be removed either, the error names it. +func TestReplaceNamesTheNewServerItCouldNotRemove(t *testing.T) { + agent := replaceAcrossSpaces() + agent.disassociateErr = errors.New("InternalServerException") + agent.deregisterErr = errors.New("ThrottlingException") + + _, err := replaceRun(t, agent) + + require.Error(t, err) + assert.ErrorContains(t, err, "could not remove the new MCP server mcp-1") + assert.ErrorContains(t, err, "--replace-mcp-token") +} + +// A run after such a failure removes the unused server with the name of the +// space, so the new registration does not fail on the name. +func TestReplaceRemovesAnUnusedServerWithTheNameOfTheSpace(t *testing.T) { + agent := replaceAcrossSpaces() + agent.services = append(agent.services, + mcpService("mcp-left", awsdevops.MCPServerNameFor("space-1"), awsdevops.MCPServerEndpoint)) + clients := newTestClients(agent, newFakeIAM()) + opts := rejectingOptions(t, http.StatusOK) + opts.ReplaceMCPToken = true + plan, err := awsdevops.PlanSetup(context.Background(), clients, opts, true) + require.NoError(t, err) + + assert.Contains(t, plan.Text().MCPServer, "Remove MCP server "+awsdevops.MCPServerNameFor("space-1")+" (mcp-left)") + _, err = awsdevops.RunPlan(context.Background(), clients, opts, plan) + require.NoError(t, err) + assert.Equal(t, []string{"mcp-left"}, agent.deregisteredIDs) + assert.Less(t, indexOf(agent.calls, "DeregisterService"), indexOf(agent.calls, "RegisterService")) +} + +// A replace gives the new server the name of the space, so a run after a +// failure can find it. The plan says so. +func TestRunPlanReplaceRenamesAnUnsharedServer(t *testing.T) { + agent := replaceOnOneSpace() + agent.services = []agenttypes.RegisteredService{mcpService("mcp-old", "Prod LD", awsdevops.MCPServerEndpoint)} + clients := newTestClients(agent, newFakeIAM()) + opts := rejectingOptions(t, http.StatusOK) + opts.ReplaceMCPToken = true + plan, err := awsdevops.PlanSetup(context.Background(), clients, opts, true) + require.NoError(t, err) + + assert.Equal(t, "Replace the token of MCP server Prod LD (mcp-old), and rename it to LaunchDarkly-space-1", + plan.Text().MCPServer) + _, err = awsdevops.RunPlan(context.Background(), clients, opts, plan) + require.NoError(t, err) + require.Len(t, agent.registerInputs, 1) + details, ok := agent.registerInputs[0].ServiceDetails.(*agenttypes.ServiceDetailsMemberMcpserver) + require.True(t, ok) + assert.Equal(t, awsdevops.MCPServerNameFor("space-1"), aws.ToString(details.Value.Name)) +} + +// A server with the name of this space that other spaces share keeps the +// name, so the new server cannot have it. The plan stops, because every run +// would fail on the name. +func TestPlanStopsWhenTheSharedServerHasTheNameOfTheSpace(t *testing.T) { + agent := replaceAcrossSpaces() + agent.services = []agenttypes.RegisteredService{ + mcpService("mcp-old", awsdevops.MCPServerNameFor("space-1"), awsdevops.MCPServerEndpoint), + } + opts := runPlanOptions() + opts.ReplaceMCPToken = true + + _, err := awsdevops.PlanSetup(context.Background(), newTestClients(agent, newFakeIAM()), opts, true) + + require.Error(t, err) + assert.ErrorContains(t, err, "other agent spaces (space-3) use it") + assert.ErrorContains(t, err, "Rename mcp-old in the AWS console") + assert.ErrorContains(t, err, "--agent-space-id --access-token --replace-mcp-token") + assert.NotContains(t, agent.calls, "RegisterService") +} + +// A disconnect that AWS made but reported as failed is a disconnect, so the +// run keeps the new server and connects it. +func TestReplaceKeepsTheNewServerWhenTheFailedDisconnectHappened(t *testing.T) { + agent := replaceAcrossSpaces() + agent.disassociateErr = errors.New("RequestTimeout") + agent.onDisassociate = func() { delete(agent.spaceLinks, "space-1") } + + result, err := replaceRun(t, agent) + + require.NoError(t, err) + assert.Empty(t, agent.deregisteredIDs) + assert.Equal(t, "mcp-1", result.MCPServiceID) + assert.Equal(t, "assoc-mcp-1", result.MCPAssociationID) +} + +// A replace on a server that only this space uses removes an unused server +// with the name of the space first, so the new server can have the name. +func TestReplaceOnAnUnsharedServerRemovesAnUnusedServerWithTheName(t *testing.T) { + agent := replaceOnOneSpace() + agent.services = append(agent.services, + mcpService("mcp-left", awsdevops.MCPServerNameFor("space-1"), awsdevops.MCPServerEndpoint)) + clients := newTestClients(agent, newFakeIAM()) + opts := rejectingOptions(t, http.StatusOK) + opts.ReplaceMCPToken = true + plan, err := awsdevops.PlanSetup(context.Background(), clients, opts, true) + require.NoError(t, err) + + assert.Equal(t, + "Remove MCP server "+awsdevops.MCPServerNameFor("space-1")+" (mcp-left), which no agent space uses. "+ + "Replace the token of MCP server LaunchDarkly (mcp-old), and rename it to "+awsdevops.MCPServerNameFor("space-1"), + plan.Text().MCPServer) + _, err = awsdevops.RunPlan(context.Background(), clients, opts, plan) + require.NoError(t, err) + assert.Equal(t, []string{"mcp-left", "mcp-old"}, agent.deregisteredIDs) +} + +// A server with the name of the space that another space uses stops the plan +// before setup removes the old server. +func TestReplaceOnAnUnsharedServerStopsWhenAnotherSpaceHasTheName(t *testing.T) { + agent := replaceOnOneSpace() + agent.services = append(agent.services, + mcpService("mcp-other", awsdevops.MCPServerNameFor("space-1"), awsdevops.MCPServerEndpoint)) + agent.spaceLinks["space-2"] = mcpLink("mcp-other") + opts := runPlanOptions() + opts.ReplaceMCPToken = true + + _, err := awsdevops.PlanSetup(context.Background(), newTestClients(agent, newFakeIAM()), opts, true) + + require.Error(t, err) + assert.ErrorContains(t, err, "other agent spaces (space-2) use it") + assert.Empty(t, agent.deregisteredIDs) +} + +// --mcp-service-id must not give a space a second LaunchDarkly server. +func TestPlanStopsWhenMCPServiceIDIsNotTheServerOfTheSpace(t *testing.T) { + for name, replace := range map[string]bool{"reuse": false, "replace": true} { + t.Run(name, func(t *testing.T) { + agent := linkedSpace("mcp-own") + agent.services = append(agent.services, launchDarklyMCPService("mcp-chosen")) + opts := runPlanOptions() + opts.MCPServiceID = "mcp-chosen" + opts.ReplaceMCPToken = replace + + _, err := awsdevops.PlanSetup(context.Background(), newTestClients(agent, newFakeIAM()), opts, true) + + require.Error(t, err) + assert.ErrorContains(t, err, "agent space space-1 already uses MCP server LaunchDarkly (mcp-own)") + }) + } +} + +// Setup cannot pick between two LaunchDarkly servers on one space. +func TestPlanStopsOnASpaceWithTwoLaunchDarklyServers(t *testing.T) { + agent := linkedSpace("mcp-a") + agent.services = append(agent.services, launchDarklyMCPService("mcp-b")) + agent.associations = append(agent.associations, mcpLink("mcp-b")...) + + _, err := awsdevops.PlanSetup(context.Background(), newTestClients(agent, newFakeIAM()), runPlanOptions(), true) + + require.Error(t, err) + assert.ErrorContains(t, err, "connected to 2 LaunchDarkly MCP servers") +} + +// A space that shares a server with other spaces acts as the account of its +// token, so the plan says so. +func TestPlanWarnsWhenTheReusedServerIsShared(t *testing.T) { + opts := runPlanOptions() + opts.LDAccessToken = "" + + plan, err := awsdevops.PlanSetup(context.Background(), newTestClients(replaceAcrossSpaces(), newFakeIAM()), opts, true) + + require.NoError(t, err) + require.Equal(t, awsdevops.MCPReuse, plan.MCP.Action) + assert.Equal(t, + "Reuse MCP server LaunchDarkly (mcp-old). Agent spaces space-3 also use it and its token. "+ + "To give this agent space its own server, pass --access-token and --replace-mcp-token", + plan.Text().MCPServer) +} + +// AWS allows only letters, digits, "_" and "-" in an MCP server name. +func TestMCPServerNameForHasOnlyAllowedCharacters(t *testing.T) { + name := awsdevops.MCPServerNameFor("0b9f6c3e-5d7a-4c1e-9a2b-3f4e5d6c7b8a") + + assert.Regexp(t, `^[a-zA-Z0-9_-]{1,128}$`, name) +} diff --git a/internal/awsdevops/setup.go b/internal/awsdevops/setup.go index 84adeac33..e0cc40922 100644 --- a/internal/awsdevops/setup.go +++ b/internal/awsdevops/setup.go @@ -71,7 +71,7 @@ type SetupOptions struct { ReplaceMCPToken bool // MCPServiceID, when set, is the registration to reuse or replace instead - // of the one found by endpoint. + // of the server of the agent space. MCPServiceID string // MCPEndpoint overrides the LaunchDarkly MCP endpoint, for an account // running the open-source MCP server itself. The endpoint identifies the @@ -317,6 +317,30 @@ type MCPStep struct { Name string // Spaces lists spaces linked to the server. Spaces []string + // SpaceID is the agent space of the step. It is empty for a new space. + SpaceID string + // Unused is a server with the name that setup gives the space, which no + // space uses. A replace on a shared server removes it first, so that the + // new server can have the name. An earlier run that failed leaves one. + Unused string +} + +// shared reports whether other spaces use the server. +func (m MCPStep) shared() bool { + return len(m.otherSpaces()) > 0 +} + +// otherSpaces lists the spaces, other than the space of the step, that use +// the server. A token replacement does not change them. +func (m MCPStep) otherSpaces() []string { + var others []string + for _, id := range m.Spaces { + if id != m.SpaceID { + others = append(others, id) + } + } + + return others } // SetupPlan describes what setup will change. It holds only the steps. Text @@ -426,7 +450,7 @@ func PlanSetup(ctx context.Context, clients Clients, opts SetupOptions, provisio return plan, err } - plan.MCP, err = planMCPStep(ctx, clients, opts) + plan.MCP, err = planMCPStep(ctx, clients, opts, plan.Space.ID) if err != nil { return plan, err } @@ -561,25 +585,41 @@ func checkSpace(ctx context.Context, clients Clients, step SpaceStep) error { return nil } -func planMCPStep(ctx context.Context, clients Clients, opts SetupOptions) (MCPStep, error) { - step, err := planMCPAction(ctx, clients, opts) +func planMCPStep(ctx context.Context, clients Clients, opts SetupOptions, spaceID string) (MCPStep, error) { + step, err := planMCPAction(ctx, clients, opts, spaceID) step.Endpoint = opts.mcpEndpoint() + step.SpaceID = spaceID return step, err } -func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions) (MCPStep, error) { - existing := opts.MCPServiceID - var name string - var err error - if existing != "" { - name, err = checkMCPServiceID(ctx, clients, existing, opts.mcpEndpoint()) - } else { - existing, name, err = findMCPService(ctx, clients, opts.mcpEndpoint()) - } +func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions, spaceID string) (MCPStep, error) { + linked, own, err := spaceMCPServers(ctx, clients, spaceID, opts.mcpEndpoint()) if err != nil { return MCPStep{}, err } + existing, name := linked.ID, linked.Name + switch { + case opts.MCPServiceID != "": + name, err = checkMCPServiceID(ctx, clients, opts.MCPServiceID, opts.mcpEndpoint()) + if err != nil { + return MCPStep{}, err + } + // A space with two LaunchDarkly servers makes the next run unable to + // pick one. + if linked.ID != "" && linked.ID != opts.MCPServiceID { + return MCPStep{}, fmt.Errorf( + "agent space %s already uses MCP server %s (%s). To use MCP server %s instead, "+ + "disconnect %s from the agent space in the AWS console, then run setup again", + spaceID, linked.Name, linked.ID, opts.MCPServiceID, linked.ID, + ) + } + existing = opts.MCPServiceID + case existing == "": + // A run that registered the server and then failed to connect it + // leaves a server with the name of the space. + existing, name = own.ID, own.Name + } switch { case existing != "" && opts.ReplaceMCPToken && opts.LDAccessToken != "": @@ -587,10 +627,34 @@ func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions) (MCP if err != nil { return MCPStep{}, err } + step := MCPStep{Action: MCPReplace, ServiceID: existing, Name: name, Spaces: spaces, SpaceID: spaceID} + // The new server gets the name of the space. A server that other + // spaces use keeps the name, so the new server cannot have it. + if step.shared() && own.ID == existing { + return MCPStep{}, nameTaken(own, spaceID, step.otherSpaces()) + } + if own.ID != "" && own.ID != existing { + users, err := spacesWith(ctx, clients, own.ID) + if err != nil { + return MCPStep{}, err + } + if len(users) > 0 { + return MCPStep{}, nameTaken(own, spaceID, users) + } + // No space uses it, so the run removes it before it registers. + step.Unused = own.ID + } - return MCPStep{Action: MCPReplace, ServiceID: existing, Name: name, Spaces: spaces}, nil + return step, nil case existing != "": - return MCPStep{Action: MCPReuse, ServiceID: existing, Name: name}, nil + // The other spaces are only for the plan text, which warns that the + // space shares a token. + spaces, err := spacesWith(ctx, clients, existing) + if err != nil { + return MCPStep{}, err + } + + return MCPStep{Action: MCPReuse, ServiceID: existing, Name: name, Spaces: spaces}, nil case opts.LDAccessToken != "": return MCPStep{Action: MCPRegister}, nil default: @@ -598,6 +662,18 @@ func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions) (MCP } } +// nameTaken is the error for a server that has the name that setup gives an +// agent space, while other agent spaces use it. +func nameTaken(own mcpRef, spaceID string, users []string) error { + return fmt.Errorf( + "MCP server %s (%s) has the name that setup gives agent space %s, and other agent spaces (%s) use it, "+ + "so setup cannot register a new server with that name. Rename %s in the AWS console, then run setup again. "+ + "Or, to move those agent spaces to their own servers, run setup with --agent-space-id "+ + "--access-token --replace-mcp-token for each one", + own.Name, own.ID, spaceID, strings.Join(users, ", "), own.ID, + ) +} + // checkMCPServiceID needs a registered MCP server at the LaunchDarkly // endpoint. Setup finds a LaunchDarkly MCP server by its endpoint, because the // name is the choice of the customer. A server at another endpoint is not one, @@ -638,16 +714,42 @@ func (m MCPStep) name() string { func (m MCPStep) describe() string { switch m.Action { case MCPReplace: - line := fmt.Sprintf("Replace the token of MCP server %s (%s)", m.name(), m.ServiceID) - if len(m.Spaces) > 0 { - line += ", reconnecting " + strings.Join(m.Spaces, ", ") + var line string + if m.shared() { + line = fmt.Sprintf( + "Register a new MCP server for this agent space at %s. MCP server %s (%s) keeps its token for %s", + m.Endpoint, m.name(), m.ServiceID, strings.Join(m.otherSpaces(), ", "), + ) + } else { + line = fmt.Sprintf("Replace the token of MCP server %s (%s)", m.name(), m.ServiceID) + // Every server that setup registers has the name of its space, + // so a run after a failure can find it. + switch { + case m.SpaceID == "": + line += ", and give it the name of the new agent space" + case m.name() != MCPServerNameFor(m.SpaceID): + line += ", and rename it to " + MCPServerNameFor(m.SpaceID) + } + } + if m.Unused != "" { + line = fmt.Sprintf("Remove MCP server %s (%s), which no agent space uses. %s", + MCPServerNameFor(m.SpaceID), m.Unused, line) } return line case MCPReuse: - return fmt.Sprintf("Reuse MCP server %s (%s)", m.name(), m.ServiceID) + line := fmt.Sprintf("Reuse MCP server %s (%s)", m.name(), m.ServiceID) + if m.shared() { + line += fmt.Sprintf( + ". Agent spaces %s also use it and its token. "+ + "To give this agent space its own server, pass --access-token and --replace-mcp-token", + strings.Join(m.otherSpaces(), ", "), + ) + } + + return line case MCPRegister: - return fmt.Sprintf("Register MCP server %s at %s", MCPServerName, m.Endpoint) + return fmt.Sprintf("Register a new MCP server for this agent space at %s", m.Endpoint) case MCPSkip: return fmt.Sprintf("Skip MCP server %s, because no token was given", MCPServerName) default: @@ -664,8 +766,9 @@ func checkSentToken(ctx context.Context, opts SetupOptions, step MCPStep) error return CheckToken(ctx, opts.LDBaseURI, opts.LDAccessToken) } -// checkMCP compares AWS with the MCP step. -func checkMCP(ctx context.Context, clients Clients, opts SetupOptions, step MCPStep) error { +// checkMCP compares AWS with the MCP step of agent space spaceID. The ID is +// empty for a space that the run creates. +func checkMCP(ctx context.Context, clients Clients, opts SetupOptions, step MCPStep, spaceID string) error { if step.Action == MCPSkip { return nil } @@ -695,12 +798,12 @@ func checkMCP(ctx context.Context, clients Clients, opts SetupOptions, step MCPS return nil } - found, err := FindMCPServer(ctx, clients, opts.mcpEndpoint()) + linked, own, err := spaceMCPServers(ctx, clients, spaceID, opts.mcpEndpoint()) if err != nil { return err } - if found != "" { - return planChanged("an MCP server appeared at %s after the plan", opts.mcpEndpoint()) + if linked.ID != "" || own.ID != "" { + return planChanged("agent space %s got an MCP server at %s after the plan", spaceID, opts.mcpEndpoint()) } return nil @@ -738,7 +841,7 @@ func RunPlan(ctx context.Context, clients Clients, opts SetupOptions, plan Setup if err := checkApp(ctx, clients, plan); err != nil { return result, err } - if err := checkMCP(ctx, clients, opts, plan.MCP); err != nil { + if err := checkMCP(ctx, clients, opts, plan.MCP, plan.Space.ID); err != nil { return result, err } if err := checkSentToken(ctx, opts, plan.MCP); err != nil { @@ -831,8 +934,9 @@ func RunPlan(ctx context.Context, clients Clients, opts SetupOptions, plan Setup // The role and association steps can take minutes. A server that appeared // or went in that time makes AWS reject the step with an error that does - // not say that the plan changed, so check the server again. - if err := checkMCP(ctx, clients, opts, plan.MCP); err != nil { + // not say that the plan changed, so check the server again. A new space + // has its ID by now. + if err := checkMCP(ctx, clients, opts, plan.MCP, result.AgentSpaceID); err != nil { return result, err } if err := registerMCPServer(ctx, clients, opts, plan.MCP, &result, logf); err != nil { @@ -907,7 +1011,7 @@ func ConnectPlan(ctx context.Context, clients Clients, opts SetupOptions, plan S } logf("Using agent space %s (%s)", plan.Space.Name, result.AgentSpaceID) - if err := checkMCP(ctx, clients, opts, plan.MCP); err != nil { + if err := checkMCP(ctx, clients, opts, plan.MCP, plan.Space.ID); err != nil { return result, err } if err := checkSentToken(ctx, opts, plan.MCP); err != nil { @@ -1011,7 +1115,7 @@ func RegisterMCPServer(ctx context.Context, clients Clients, opts SetupOptions, if logf == nil { logf = func(string, ...any) {} } - if err := checkMCP(ctx, clients, opts, step); err != nil { + if err := checkMCP(ctx, clients, opts, step, result.AgentSpaceID); err != nil { return err } if step.Action == MCPAsk { @@ -1050,6 +1154,8 @@ func registerMCPServer( return associateMCPServer(ctx, clients, result, logf) } + // A run after a failure finds an unconnected server by this name. + name := MCPServerNameFor(result.AgentSpaceID) var detached []string if existing != "" { // Narrow the window after other writes. @@ -1060,6 +1166,16 @@ func registerMCPServer( if !slices.Equal(now, step.Spaces) { return planChanged("the spaces using MCP server %s changed", existing) } + } + if step.Unused != "" { + if err := removeUnused(ctx, clients, step.Unused, logf); err != nil { + return err + } + } + // Other spaces keep a shared server with its token. Only a server that no + // other space uses is removed. + if existing != "" && !step.shared() { + var err error detached, err = disassociateEverywhere(ctx, clients, existing, logf) if err != nil { return err @@ -1082,12 +1198,11 @@ func registerMCPServer( logf("Removed MCP server %s (%s) to replace its token", step.name(), existing) } - // A replaced server keeps its name, as the plan says. input := &devopsagent.RegisterServiceInput{ Service: agenttypes.PostRegisterServiceSupportedServiceMcpServer, ServiceDetails: &agenttypes.ServiceDetailsMemberMcpserver{ Value: agenttypes.MCPServerDetails{ - Name: aws.String(step.name()), + Name: aws.String(name), Endpoint: aws.String(endpoint), Description: aws.String("LaunchDarkly feature flag management MCP server"), AuthorizationConfig: &agenttypes.MCPServerAuthorizationConfigMemberBearerToken{ @@ -1103,12 +1218,14 @@ func registerMCPServer( registration, err := registerWithRetry(ctx, clients, input, logf, endpoint) if err != nil { if strings.Contains(err.Error(), "already exists") { - // Another server at another endpoint has the name. It is not a - // LaunchDarkly server at this endpoint, so setup cannot use it. + // The plan removes or stops on a server at this endpoint with the + // name, so the server is at another endpoint, or it appeared + // after the plan. err = fmt.Errorf( - "an MCP server named %s is already registered on this account at another endpoint, "+ - "so %s cannot be registered. Rename that server in the AWS console: %w", - step.name(), endpoint, err, + "an MCP server named %s is already registered on this account, so setup cannot register "+ + "one at %s with that name. If that server is at another endpoint, rename it in the AWS console. "+ + "Otherwise, run setup again: %w", + name, endpoint, err, ) } @@ -1116,37 +1233,91 @@ func registerMCPServer( } result.MCPServiceID = aws.ToString(registration.ServiceId) - logf("Registered MCP server %s (%s)", step.name(), result.MCPServiceID) - - // Reconnect the other spaces even if this one fails, so that a failure - // disconnects as few spaces as possible. - assocErr := associateMCPServer(ctx, clients, result, logf) - - // The deregistered service was account-level, so reconnect the other agent - // spaces that were using it before the token was replaced. - var lost []string - var lostErr error - for _, agentSpaceID := range detached { - if agentSpaceID == result.AgentSpaceID { - continue + logf("Registered MCP server %s (%s)", name, result.MCPServiceID) + + if existing != "" && step.shared() { + if err := leaveSharedServer(ctx, clients, step, result, logf); err != nil { + return err } - if _, err := associateMCPServerWith(ctx, clients, agentSpaceID, result.MCPServiceID); err != nil { - lost = append(lost, agentSpaceID) - lostErr = errors.Join(lostErr, err) + } - continue + return associateMCPServer(ctx, clients, result, logf) +} + +// leaveSharedServer disconnects a shared server from this space only, after +// the new server is registered. The other spaces keep it with its token. If +// the disconnect fails, it removes the new server, so that the space stays as +// it was and a run again plans the same steps. +func leaveSharedServer(ctx context.Context, clients Clients, step MCPStep, result *SetupResult, logf func(string, ...any)) error { + link, err := FindAssociation(ctx, clients, result.AgentSpaceID, step.ServiceID) + if err == nil && link != "" { + _, err = clients.Agent.DisassociateService(ctx, &devopsagent.DisassociateServiceInput{ + AgentSpaceId: aws.String(result.AgentSpaceID), + AssociationId: aws.String(link), + }) + } + var checkErr error + if err != nil { + // A disconnect can fail in the reply after AWS made it, so look + // again before the new server is removed. + var still string + still, checkErr = FindAssociation(ctx, clients, result.AgentSpaceID, step.ServiceID) + if checkErr == nil && still == "" { + err = nil } - logf("Associated MCP server %s with agent space (%s) again", MCPServerName, agentSpaceID) } - if len(lost) > 0 { - lostErr = fmt.Errorf( - "agent spaces %s lost the LaunchDarkly MCP server when its token was replaced. "+ - "To connect each one again, run setup with --agent-space-id : %w", - strings.Join(lost, ", "), lostErr, + if err == nil { + if link != "" { + logf("Disconnected MCP server %s (%s) from the agent space. Agent spaces %s keep it", + step.name(), step.ServiceID, strings.Join(step.otherSpaces(), ", ")) + } + + return nil + } + + err = fmt.Errorf("unable to disconnect MCP server %s from agent space %s: %w", step.ServiceID, result.AgentSpaceID, err) + created := result.MCPServiceID + result.MCPServiceID = "" + if _, removeErr := clients.Agent.DeregisterService(ctx, &devopsagent.DeregisterServiceInput{ + ServiceId: aws.String(created), + }); removeErr != nil { + // A run again removes the new server, because no space uses it. + return fmt.Errorf( + "%w. Setup also could not remove the new MCP server %s, which no agent space uses. "+ + "Run setup again with --replace-mcp-token: %w", + err, created, removeErr, ) } + if checkErr != nil { + logf("Removed the new MCP server (%s)", created) + + return fmt.Errorf("%w. Setup could not check if the agent space still uses MCP server %s: %w", + err, step.ServiceID, checkErr) + } + + logf("Removed the new MCP server (%s), because the agent space still uses MCP server %s", created, step.ServiceID) + + return fmt.Errorf("%w. The agent space still uses MCP server %s with its old token", err, step.ServiceID) +} - return errors.Join(assocErr, lostErr) +// removeUnused removes a server that no space uses, after a check that this +// is still true. +func removeUnused(ctx context.Context, clients Clients, serviceID string, logf func(string, ...any)) error { + users, err := spacesWith(ctx, clients, serviceID) + if err != nil { + return err + } + if len(users) > 0 { + return planChanged("agent spaces %s started to use MCP server %s after the plan", strings.Join(users, ", "), serviceID) + } + if _, err := clients.Agent.DeregisterService(ctx, &devopsagent.DeregisterServiceInput{ + ServiceId: aws.String(serviceID), + }); err != nil { + return fmt.Errorf("unable to remove MCP server %s, which no agent space uses: %w", serviceID, err) + } + logf("Removed MCP server (%s), which no agent space used", serviceID) + + return nil } // spacesWith lists spaces associated with serviceID. diff --git a/internal/awsdevops/setup_test.go b/internal/awsdevops/setup_test.go index 38592ce34..d2fadc469 100644 --- a/internal/awsdevops/setup_test.go +++ b/internal/awsdevops/setup_test.go @@ -54,7 +54,7 @@ func TestSetupProgressLinesHaveNoARNs(t *testing.T) { }, iam: newFakeIAM(), opts: awsdevops.SetupOptions{ - AgentSpaceName: "launchdarkly", + AgentSpaceID: "space-1", AuthFlow: "iam", LDAccessToken: "api-token", ReplaceMCPToken: true, @@ -225,8 +225,8 @@ func TestPlanSetupNamesTheMCPServerAction(t *testing.T) { } for name, c := range cases { t.Run(name, func(t *testing.T) { - c.opts.AgentSpaceName = "launchdarkly" - agent := &fakeAgent{services: c.services} + c.opts.AgentSpaceID = "space-1" + agent := &fakeAgent{services: c.services, associations: mcpLink("mcp-existing")} plan, err := awsdevops.PlanSetup(context.Background(), newTestClients(agent, newFakeIAM()), c.opts, true) require.NoError(t, err)