From 7be840b4b3e88b172a70afc35db625e011dbd9d7 Mon Sep 17 00:00:00 2001 From: Christina Chu Date: Mon, 26 Oct 2026 09:55:32 -0700 Subject: [PATCH 1/5] fix: give each agent space its own LaunchDarkly MCP server Setup found the LaunchDarkly MCP server by its endpoint and reused it for every agent space in the account and region. All spaces then used the token of the first run, and a token replacement changed the token of every space. Setup now finds the server of a space by its association. A space with no server gets a new server named "LaunchDarkly ". With --replace-mcp-token, only the chosen space changes. If other spaces use the old server, they keep it and its token. Co-Authored-By: Claude Opus 5.5 --- cmd/aws_devops_agent/plan_print_test.go | 21 +++-- cmd/aws_devops_agent/select_test.go | 4 +- cmd/aws_devops_agent/setup.go | 18 ++-- internal/awsdevops/awsdevops_test.go | 54 ++--------- internal/awsdevops/lookup.go | 47 +++++++--- internal/awsdevops/lookup_test.go | 104 +++++++++++++++------ internal/awsdevops/plan_test.go | 29 ++++-- internal/awsdevops/runplan_test.go | 88 ++++++++++-------- internal/awsdevops/setup.go | 116 ++++++++++++++---------- internal/awsdevops/setup_test.go | 4 +- 10 files changed, 286 insertions(+), 199 deletions(-) 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..3f2c7579d 100644 --- a/internal/awsdevops/awsdevops_test.go +++ b/internal/awsdevops/awsdevops_test.go @@ -363,8 +363,8 @@ 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"}, + // A new space has no MCP server, so setup does not look for one. + []string{"CreateAgentSpace", "AssociateService", "EnableOperatorApp", "RegisterService", "AssociateService"}, agent.calls, ) } @@ -501,12 +501,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 +539,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 +554,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 +577,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 +595,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..b94ceae0b 100644 --- a/internal/awsdevops/lookup.go +++ b/internal/awsdevops/lookup.go @@ -197,29 +197,50 @@ 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) - - return id, err +// MCPServerNameFor is the name of the MCP server that setup registers for an +// agent space. AWS needs a unique name, and the ID ties the server to the space. +func MCPServerNameFor(agentSpaceID string) string { + return MCPServerName + " " + agentSpaceID } -// 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) { +// spaceMCPService returns the ID and the name of the MCP server of an agent +// space. That is the server at endpoint that the space is connected to. If +// there is none, it is the server at endpoint that setup registered for the +// space. 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. +func spaceMCPService(ctx context.Context, clients Clients, agentSpaceID, endpoint string) (id, name string, err error) { + // A new space has no ID and no server yet. + if agentSpaceID == "" { + return "", "", nil + } + associations, err := listAssociations(ctx, clients, agentSpaceID) + if err != nil { + return "", "", err + } + linked := make(map[string]bool, len(associations)) + for _, association := range associations { + linked[aws.ToString(association.ServiceId)] = true + } services, err := listServices(ctx, clients) if err != nil { return "", "", err } for _, service := range services { - if mcpEndpointOf(service) == endpoint { - return aws.ToString(service.ServiceId), serviceName(service), nil + if mcpEndpointOf(service) != endpoint { + continue + } + serviceID := aws.ToString(service.ServiceId) + if linked[serviceID] { + return serviceID, serviceName(service), nil + } + // A run that registered the server and then failed to connect it + // leaves a server with the name of the space. + if id == "" && serviceName(service) == MCPServerNameFor(agentSpaceID) { + id, name = serviceID, serviceName(service) } } - return "", "", nil + return id, name, 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..28cd04185 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,9 +1009,9 @@ 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") @@ -1012,27 +1019,40 @@ func TestRunPlanReplaceNameClashNamesTheDisconnectedSpaces(t *testing.T) { 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.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 that server 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,13 @@ 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), + } +} diff --git a/internal/awsdevops/setup.go b/internal/awsdevops/setup.go index 84adeac33..361cb3f29 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,21 @@ 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 +} + +// 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 +441,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,21 +576,22 @@ 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) { +func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions, spaceID string) (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()) + existing, name, err = spaceMCPService(ctx, clients, spaceID, opts.mcpEndpoint()) } if err != nil { return MCPStep{}, err @@ -638,16 +654,19 @@ 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, ", ") + others := m.otherSpaces() + if len(others) == 0 { + return fmt.Sprintf("Replace the token of MCP server %s (%s)", m.name(), m.ServiceID) } - return line + return 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(others, ", "), + ) case MCPReuse: return fmt.Sprintf("Reuse MCP server %s (%s)", m.name(), m.ServiceID) 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 +683,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 +715,12 @@ func checkMCP(ctx context.Context, clients Clients, opts SetupOptions, step MCPS return nil } - found, err := FindMCPServer(ctx, clients, opts.mcpEndpoint()) + found, _, err := spaceMCPService(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()) + return planChanged("agent space %s got an MCP server at %s after the plan", spaceID, opts.mcpEndpoint()) } return nil @@ -738,7 +758,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 { @@ -832,7 +852,7 @@ 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 { + if err := checkMCP(ctx, clients, opts, plan.MCP, plan.Space.ID); err != nil { return result, err } if err := registerMCPServer(ctx, clients, opts, plan.MCP, &result, logf); err != nil { @@ -907,7 +927,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 +1031,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,7 +1070,9 @@ func registerMCPServer( return associateMCPServer(ctx, clients, result, logf) } + name := MCPServerNameFor(result.AgentSpaceID) var detached []string + shared := false if existing != "" { // Narrow the window after other writes. now, err := spacesWith(ctx, clients, existing) @@ -1060,6 +1082,12 @@ func registerMCPServer( if !slices.Equal(now, step.Spaces) { return planChanged("the spaces using MCP server %s changed", existing) } + // Other spaces keep a shared server with its token. Only a server that + // no other space uses is removed. + shared = len(step.otherSpaces()) > 0 + } + if existing != "" && !shared { + var err error detached, err = disassociateEverywhere(ctx, clients, existing, logf) if err != nil { return err @@ -1082,12 +1110,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{ @@ -1108,7 +1135,7 @@ func registerMCPServer( 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, + name, endpoint, err, ) } @@ -1116,37 +1143,28 @@ 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 - } - if _, err := associateMCPServerWith(ctx, clients, agentSpaceID, result.MCPServiceID); err != nil { - lost = append(lost, agentSpaceID) - lostErr = errors.Join(lostErr, err) + logf("Registered MCP server %s (%s)", name, result.MCPServiceID) - continue + if shared { + // Disconnect the shared server from this space only. The other spaces + // keep it with its token. + link, err := FindAssociation(ctx, clients, result.AgentSpaceID, existing) + if err != nil { + return err + } + if link != "" { + if _, err := clients.Agent.DisassociateService(ctx, &devopsagent.DisassociateServiceInput{ + AgentSpaceId: aws.String(result.AgentSpaceID), + AssociationId: aws.String(link), + }); err != nil { + return fmt.Errorf("unable to disconnect MCP server %s from agent space %s: %w", existing, result.AgentSpaceID, err) + } + logf("Disconnected MCP server %s (%s) from the agent space. Agent spaces %s keep it", + step.name(), existing, strings.Join(step.otherSpaces(), ", ")) } - 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, - ) } - return errors.Join(assocErr, lostErr) + return associateMCPServer(ctx, clients, result, logf) } // spacesWith lists spaces associated with serviceID. diff --git a/internal/awsdevops/setup_test.go b/internal/awsdevops/setup_test.go index 38592ce34..1bea544d0 100644 --- a/internal/awsdevops/setup_test.go +++ b/internal/awsdevops/setup_test.go @@ -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) From 666b6b75a8da922284517ac4f8e3eed17065bb91 Mon Sep 17 00:00:00 2001 From: Christina Chu Date: Mon, 26 Oct 2026 10:06:50 -0700 Subject: [PATCH 2/5] fix: make the MCP server replacement safe on a shared server AWS allows only letters, digits, "_" and "-" in an MCP server name, so the server of a space is now named "LaunchDarkly-". A replace on a shared server removes the new server if the old server cannot be disconnected, so the space stays as it was. A run after a failure removes an unused server with the name of the space before it registers the new one. A replace on a server that only this space uses keeps the name of the server, as the plan says. The plan now warns when a reused server is shared with other spaces. Setup stops if a space is connected to more than one LaunchDarkly server, or if --mcp-service-id names a server other than the server of the space. The check before the MCP step uses the ID of a new space. Co-Authored-By: Claude Opus 5.5 --- internal/awsdevops/awsdevops_test.go | 9 +- internal/awsdevops/lookup.go | 58 +++++--- internal/awsdevops/runplan_test.go | 120 +++++++++++++++- internal/awsdevops/setup.go | 199 +++++++++++++++++++++------ internal/awsdevops/setup_test.go | 2 +- 5 files changed, 320 insertions(+), 68 deletions(-) diff --git a/internal/awsdevops/awsdevops_test.go b/internal/awsdevops/awsdevops_test.go index 3f2c7579d..2ee97af54 100644 --- a/internal/awsdevops/awsdevops_test.go +++ b/internal/awsdevops/awsdevops_test.go @@ -50,6 +50,7 @@ type fakeAgent struct { registerOutput *devopsagent.RegisterServiceOutput registerErr error deregisterErr error + disassociateErr error registerInputs []*devopsagent.RegisterServiceInput associations []agenttypes.Association agentSpaces []agenttypes.AgentSpace @@ -123,6 +124,9 @@ 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.disassociateErr != nil { + return nil, f.disassociateErr + } f.disassociatedIDs = append(f.disassociatedIDs, aws.ToString(in.AssociationId)) return &devopsagent.DisassociateServiceOutput{}, nil @@ -363,8 +367,9 @@ func TestSetupCreatesRolesAgentSpaceAndAssociations(t *testing.T) { assert.Contains(t, iamClient.inlinePolicies[awsdevops.AgentSpaceRoleName], "iam:CreateServiceLinkedRole") assert.Equal( t, - // A new space has no MCP server, so setup does not look for one. - []string{"CreateAgentSpace", "AssociateService", "EnableOperatorApp", "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, ) } diff --git a/internal/awsdevops/lookup.go b/internal/awsdevops/lookup.go index b94ceae0b..444d41e46 100644 --- a/internal/awsdevops/lookup.go +++ b/internal/awsdevops/lookup.go @@ -198,49 +198,65 @@ func agentSpaceARN(region, accountID, spaceID string) string { } // MCPServerNameFor is the name of the MCP server that setup registers for an -// agent space. AWS needs a unique name, and the ID ties the server to the space. +// 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 MCPServerName + "-" + agentSpaceID } -// spaceMCPService returns the ID and the name of the MCP server of an agent -// space. That is the server at endpoint that the space is connected to. If -// there is none, it is the server at endpoint that setup registered for the -// space. 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. -func spaceMCPService(ctx context.Context, clients Clients, agentSpaceID, endpoint string) (id, name string, err error) { +// mcpRef identifies a registered MCP server. +type mcpRef struct { + ID string + Name string +} + +// 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 "", "", nil + return mcpRef{}, mcpRef{}, nil } associations, err := listAssociations(ctx, clients, agentSpaceID) if err != nil { - return "", "", err + return mcpRef{}, mcpRef{}, err } - linked := make(map[string]bool, len(associations)) + links := make(map[string]bool, len(associations)) for _, association := range associations { - linked[aws.ToString(association.ServiceId)] = true + 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 { continue } - serviceID := aws.ToString(service.ServiceId) - if linked[serviceID] { - return serviceID, serviceName(service), nil + 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)) } - // A run that registered the server and then failed to connect it - // leaves a server with the name of the space. - if id == "" && serviceName(service) == MCPServerNameFor(agentSpaceID) { - id, name = serviceID, serviceName(service) + 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 id, name, nil + return linked, own, nil } // spacesNamed lists IDs of spaces named name. diff --git a/internal/awsdevops/runplan_test.go b/internal/awsdevops/runplan_test.go index 28cd04185..b7e263cce 100644 --- a/internal/awsdevops/runplan_test.go +++ b/internal/awsdevops/runplan_test.go @@ -1018,7 +1018,7 @@ func TestRunPlanReplaceNameClashKeepsTheSharedServer(t *testing.T) { _, err := replaceRun(t, agent) require.Error(t, err) - assert.ErrorContains(t, err, "Rename that server in the AWS console") + 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) @@ -1033,7 +1033,7 @@ func TestRunPlanReplaceNameClashNamesTheDisconnectedSpace(t *testing.T) { _, err := replaceRun(t, agent) require.Error(t, err) - assert.ErrorContains(t, err, "Rename that server in the AWS console") + 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 ") } @@ -1166,3 +1166,119 @@ func linkedSpace(serviceID string) *fakeAgent { 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 on a server that only this space uses keeps the name of the +// server, as the plan says. +func TestRunPlanReplaceKeepsTheNameOfAnUnsharedServer(t *testing.T) { + agent := replaceOnOneSpace() + agent.services = []agenttypes.RegisteredService{mcpService("mcp-old", "Prod LD", awsdevops.MCPServerEndpoint)} + + _, err := replaceRun(t, agent) + + 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, "Prod LD", aws.ToString(details.Value.Name)) +} + +// --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 361cb3f29..0f6cb6ae1 100644 --- a/internal/awsdevops/setup.go +++ b/internal/awsdevops/setup.go @@ -319,6 +319,15 @@ type MCPStep struct { 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 @@ -585,17 +594,32 @@ func planMCPStep(ctx context.Context, clients Clients, opts SetupOptions, spaceI } func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions, spaceID string) (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 = spaceMCPService(ctx, clients, spaceID, opts.mcpEndpoint()) - } + 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 != "": @@ -603,10 +627,32 @@ func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions, spac if err != nil { return MCPStep{}, err } + step := MCPStep{Action: MCPReplace, ServiceID: existing, Name: name, Spaces: spaces, SpaceID: spaceID} + if step.shared() && own.ID != "" && own.ID != existing { + users, err := spacesWith(ctx, clients, own.ID) + if err != nil { + return MCPStep{}, err + } + if len(users) > 0 { + return MCPStep{}, fmt.Errorf( + "MCP server %s (%s) has the name that setup gives agent space %s, but agent spaces %s use it. "+ + "Rename it in the AWS console, then run setup again", + own.Name, own.ID, spaceID, strings.Join(users, ", "), + ) + } + 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: @@ -654,17 +700,30 @@ func (m MCPStep) name() string { func (m MCPStep) describe() string { switch m.Action { case MCPReplace: - others := m.otherSpaces() - if len(others) == 0 { + if !m.shared() { return fmt.Sprintf("Replace the token of MCP server %s (%s)", m.name(), m.ServiceID) } - - return fmt.Sprintf( + 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(others, ", "), + m.Endpoint, m.name(), m.ServiceID, strings.Join(m.otherSpaces(), ", "), ) + 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 a new MCP server for this agent space at %s", m.Endpoint) case MCPSkip: @@ -715,11 +774,11 @@ func checkMCP(ctx context.Context, clients Clients, opts SetupOptions, step MCPS return nil } - found, _, err := spaceMCPService(ctx, clients, spaceID, opts.mcpEndpoint()) + linked, own, err := spaceMCPServers(ctx, clients, spaceID, opts.mcpEndpoint()) if err != nil { return err } - if found != "" { + if linked.ID != "" || own.ID != "" { return planChanged("agent space %s got an MCP server at %s after the plan", spaceID, opts.mcpEndpoint()) } @@ -851,8 +910,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, plan.Space.ID); 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 { @@ -1071,8 +1131,12 @@ func registerMCPServer( return associateMCPServer(ctx, clients, result, logf) } name := MCPServerNameFor(result.AgentSpaceID) + if existing != "" && !step.shared() { + // The new server takes the place of the old one, so it keeps its + // name, as the plan says. + name = step.name() + } var detached []string - shared := false if existing != "" { // Narrow the window after other writes. now, err := spacesWith(ctx, clients, existing) @@ -1082,11 +1146,15 @@ func registerMCPServer( if !slices.Equal(now, step.Spaces) { return planChanged("the spaces using MCP server %s changed", existing) } - // Other spaces keep a shared server with its token. Only a server that - // no other space uses is removed. - shared = len(step.otherSpaces()) > 0 } - if existing != "" && !shared { + 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 { @@ -1130,11 +1198,12 @@ 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 finds 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", + "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, ) } @@ -1145,26 +1214,72 @@ func registerMCPServer( result.MCPServiceID = aws.ToString(registration.ServiceId) logf("Registered MCP server %s (%s)", name, result.MCPServiceID) - if shared { - // Disconnect the shared server from this space only. The other spaces - // keep it with its token. - link, err := FindAssociation(ctx, clients, result.AgentSpaceID, existing) - if err != nil { + if existing != "" && step.shared() { + if err := leaveSharedServer(ctx, clients, step, result, logf); err != nil { return err } + } + + 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), + }) + } + if err == nil { if link != "" { - if _, err := clients.Agent.DisassociateService(ctx, &devopsagent.DisassociateServiceInput{ - AgentSpaceId: aws.String(result.AgentSpaceID), - AssociationId: aws.String(link), - }); err != nil { - return fmt.Errorf("unable to disconnect MCP server %s from agent space %s: %w", existing, result.AgentSpaceID, err) - } logf("Disconnected MCP server %s (%s) from the agent space. Agent spaces %s keep it", - step.name(), existing, strings.Join(step.otherSpaces(), ", ")) + step.name(), step.ServiceID, strings.Join(step.otherSpaces(), ", ")) } + + return nil } - return associateMCPServer(ctx, clients, result, logf) + 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, + ) + } + 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) +} + +// 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 1bea544d0..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, From f96f3e5dae5c35172742742476ae84c5ec9c788a Mon Sep 17 00:00:00 2001 From: Christina Chu Date: Mon, 26 Oct 2026 10:12:59 -0700 Subject: [PATCH 3/5] fix: give every replaced MCP server the name of its agent space A replace now always names the new server LaunchDarkly-, and the plan says when this renames the server. Before, a replace on an unshared server kept the old name, so a run after a failed association could not find the new server, and it stayed behind with a live token. A replace stops at plan time when the shared server already has the name of the space. The new server cannot have that name, so every run failed on the name. The error tells the user to move the other spaces to their own servers first. After a failed disconnect, setup checks the association again before it says which server the space uses. Co-Authored-By: Claude Opus 5.5 --- internal/awsdevops/awsdevops_test.go | 5 +++ internal/awsdevops/runplan_test.go | 51 ++++++++++++++++++++++++---- internal/awsdevops/setup.go | 46 +++++++++++++++++++------ 3 files changed, 86 insertions(+), 16 deletions(-) diff --git a/internal/awsdevops/awsdevops_test.go b/internal/awsdevops/awsdevops_test.go index 2ee97af54..7dd86a549 100644 --- a/internal/awsdevops/awsdevops_test.go +++ b/internal/awsdevops/awsdevops_test.go @@ -51,6 +51,8 @@ type fakeAgent struct { registerErr error deregisterErr error disassociateErr error + // onDisassociate runs before DisassociateService returns. + onDisassociate func() registerInputs []*devopsagent.RegisterServiceInput associations []agenttypes.Association agentSpaces []agenttypes.AgentSpace @@ -124,6 +126,9 @@ 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 } diff --git a/internal/awsdevops/runplan_test.go b/internal/awsdevops/runplan_test.go index b7e263cce..e06a786d6 100644 --- a/internal/awsdevops/runplan_test.go +++ b/internal/awsdevops/runplan_test.go @@ -1215,19 +1215,58 @@ func TestReplaceRemovesAnUnusedServerWithTheNameOfTheSpace(t *testing.T) { assert.Less(t, indexOf(agent.calls, "DeregisterService"), indexOf(agent.calls, "RegisterService")) } -// A replace on a server that only this space uses keeps the name of the -// server, as the plan says. -func TestRunPlanReplaceKeepsTheNameOfAnUnsharedServer(t *testing.T) { +// 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) - _, err := replaceRun(t, agent) - + 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, "Prod LD", aws.ToString(details.Value.Name)) + 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, "agent spaces space-3 also use it") + assert.ErrorContains(t, err, "--replace-mcp-token on each of those agent spaces first") + assert.NotContains(t, agent.calls, "RegisterService") +} + +// A disconnect that AWS made but reported as failed leaves the space with no +// server after setup removes the new one, so the message says that. +func TestReplaceSaysWhenTheFailedDisconnectHappened(t *testing.T) { + agent := replaceAcrossSpaces() + agent.disassociateErr = errors.New("RequestTimeout") + agent.onDisassociate = func() { delete(agent.spaceLinks, "space-1") } + + _, err := replaceRun(t, agent) + + require.Error(t, err) + assert.ErrorContains(t, err, "has no LaunchDarkly MCP server now") + assert.NotContains(t, err.Error(), "still uses") } // --mcp-service-id must not give a space a second LaunchDarkly server. diff --git a/internal/awsdevops/setup.go b/internal/awsdevops/setup.go index 0f6cb6ae1..61862b0b7 100644 --- a/internal/awsdevops/setup.go +++ b/internal/awsdevops/setup.go @@ -628,7 +628,18 @@ func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions, spac return MCPStep{}, err } step := MCPStep{Action: MCPReplace, ServiceID: existing, Name: name, Spaces: spaces, SpaceID: spaceID} - if step.shared() && own.ID != "" && own.ID != existing { + if step.shared() && own.ID == existing { + // The shared server keeps the name, so the new server of this + // space cannot have it. When the other spaces move to their own + // servers, this space is the only one left, and a replace works. + return MCPStep{}, fmt.Errorf( + "MCP server %s (%s) has the name of agent space %s, but agent spaces %s also use it, "+ + "so setup cannot register a new server with that name. Run setup with --access-token and "+ + "--replace-mcp-token on each of those agent spaces first, then run this command again", + own.Name, own.ID, spaceID, strings.Join(step.otherSpaces(), ", "), + ) + } + if step.shared() && own.ID != "" { users, err := spacesWith(ctx, clients, own.ID) if err != nil { return MCPStep{}, err @@ -701,7 +712,17 @@ func (m MCPStep) describe() string { switch m.Action { case MCPReplace: if !m.shared() { - return fmt.Sprintf("Replace the token of MCP server %s (%s)", m.name(), m.ServiceID) + 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) + } + + return line } line := fmt.Sprintf( "Register a new MCP server for this agent space at %s. MCP server %s (%s) keeps its token for %s", @@ -1130,12 +1151,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) - if existing != "" && !step.shared() { - // The new server takes the place of the old one, so it keeps its - // name, as the plan says. - name = step.name() - } var detached []string if existing != "" { // Narrow the window after other writes. @@ -1257,9 +1274,18 @@ func leaveSharedServer(ctx context.Context, clients Clients, step MCPStep, resul err, created, removeErr, ) } - 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) + logf("Removed the new MCP server (%s)", created) + // A disconnect can fail in the reply after AWS made it, so look again. + still, checkErr := FindAssociation(ctx, clients, result.AgentSpaceID, step.ServiceID) + switch { + case checkErr != nil: + return fmt.Errorf("%w. Setup could not check if the agent space still uses MCP server %s: %w", + err, step.ServiceID, checkErr) + case still != "": + return fmt.Errorf("%w. The agent space still uses MCP server %s with its old token", err, step.ServiceID) + default: + return fmt.Errorf("%w. The agent space has no LaunchDarkly MCP server now. Run setup again with --access-token", err) + } } // removeUnused removes a server that no space uses, after a check that this From 364b9bb18571416fc9839dacc971a7cc35dcdbb5 Mon Sep 17 00:00:00 2001 From: Christina Chu Date: Mon, 26 Oct 2026 10:21:36 -0700 Subject: [PATCH 4/5] fix: remove an unused server with the space name on every replace A replace now removes an unused server with the name of the space on an unshared server too, and the plan says so. Before, the registration failed on the name after setup had already removed the old server, so the space had no server. After a failed disconnect from a shared server, setup checks the association before it removes the new server. If AWS made the disconnect, the run keeps the new server and connects it. The error for a server that has the name of the space now offers a rename in the AWS console first. It names the other agent spaces and shows how to choose each one with --agent-space-id. Co-Authored-By: Claude Opus 5.5 --- internal/awsdevops/runplan_test.go | 56 ++++++++++++++++++---- internal/awsdevops/setup.go | 77 +++++++++++++++++------------- 2 files changed, 91 insertions(+), 42 deletions(-) diff --git a/internal/awsdevops/runplan_test.go b/internal/awsdevops/runplan_test.go index e06a786d6..5bd351dda 100644 --- a/internal/awsdevops/runplan_test.go +++ b/internal/awsdevops/runplan_test.go @@ -1250,23 +1250,63 @@ func TestPlanStopsWhenTheSharedServerHasTheNameOfTheSpace(t *testing.T) { _, err := awsdevops.PlanSetup(context.Background(), newTestClients(agent, newFakeIAM()), opts, true) require.Error(t, err) - assert.ErrorContains(t, err, "agent spaces space-3 also use it") - assert.ErrorContains(t, err, "--replace-mcp-token on each of those agent spaces first") + 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 leaves the space with no -// server after setup removes the new one, so the message says that. -func TestReplaceSaysWhenTheFailedDisconnectHappened(t *testing.T) { +// 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") } - _, err := replaceRun(t, agent) + 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, "has no LaunchDarkly MCP server now") - assert.NotContains(t, err.Error(), "still uses") + 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. diff --git a/internal/awsdevops/setup.go b/internal/awsdevops/setup.go index 61862b0b7..18e79ed02 100644 --- a/internal/awsdevops/setup.go +++ b/internal/awsdevops/setup.go @@ -628,29 +628,20 @@ func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions, spac 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 { - // The shared server keeps the name, so the new server of this - // space cannot have it. When the other spaces move to their own - // servers, this space is the only one left, and a replace works. - return MCPStep{}, fmt.Errorf( - "MCP server %s (%s) has the name of agent space %s, but agent spaces %s also use it, "+ - "so setup cannot register a new server with that name. Run setup with --access-token and "+ - "--replace-mcp-token on each of those agent spaces first, then run this command again", - own.Name, own.ID, spaceID, strings.Join(step.otherSpaces(), ", "), - ) + return MCPStep{}, nameTaken(own, spaceID, step.otherSpaces()) } - if step.shared() && own.ID != "" { + 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{}, fmt.Errorf( - "MCP server %s (%s) has the name that setup gives agent space %s, but agent spaces %s use it. "+ - "Rename it in the AWS console, then run setup again", - own.Name, own.ID, spaceID, strings.Join(users, ", "), - ) + return MCPStep{}, nameTaken(own, spaceID, users) } + // No space uses it, so the run removes it before it registers. step.Unused = own.ID } @@ -671,6 +662,18 @@ func planMCPAction(ctx context.Context, clients Clients, opts SetupOptions, spac } } +// 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, @@ -711,8 +714,14 @@ func (m MCPStep) name() string { func (m MCPStep) describe() string { switch m.Action { case MCPReplace: - if !m.shared() { - line := fmt.Sprintf("Replace the token of MCP server %s (%s)", m.name(), m.ServiceID) + 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 { @@ -721,13 +730,7 @@ func (m MCPStep) describe() string { case m.name() != MCPServerNameFor(m.SpaceID): line += ", and rename it to " + MCPServerNameFor(m.SpaceID) } - - return line } - 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(), ", "), - ) if m.Unused != "" { line = fmt.Sprintf("Remove MCP server %s (%s), which no agent space uses. %s", MCPServerNameFor(m.SpaceID), m.Unused, line) @@ -1215,8 +1218,9 @@ func registerMCPServer( registration, err := registerWithRetry(ctx, clients, input, logf, endpoint) if err != nil { if strings.Contains(err.Error(), "already exists") { - // The plan finds a server at this endpoint with the name, so the - // server is at another endpoint, or it appeared after the plan. + // 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, so setup cannot register "+ "one at %s with that name. If that server is at another endpoint, rename it in the AWS console. "+ @@ -1252,6 +1256,16 @@ func leaveSharedServer(ctx context.Context, clients Clients, step MCPStep, resul 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 + } + } if err == nil { if link != "" { logf("Disconnected MCP server %s (%s) from the agent space. Agent spaces %s keep it", @@ -1274,18 +1288,13 @@ func leaveSharedServer(ctx context.Context, clients Clients, step MCPStep, resul err, created, removeErr, ) } - logf("Removed the new MCP server (%s)", created) - // A disconnect can fail in the reply after AWS made it, so look again. - still, checkErr := FindAssociation(ctx, clients, result.AgentSpaceID, step.ServiceID) - switch { - case checkErr != nil: + logf("Removed the new MCP server (%s), because the agent space still uses MCP server %s", created, step.ServiceID) + if checkErr != nil { return fmt.Errorf("%w. Setup could not check if the agent space still uses MCP server %s: %w", err, step.ServiceID, checkErr) - case still != "": - return fmt.Errorf("%w. The agent space still uses MCP server %s with its old token", err, step.ServiceID) - default: - return fmt.Errorf("%w. The agent space has no LaunchDarkly MCP server now. Run setup again with --access-token", err) } + + return fmt.Errorf("%w. The agent space still uses MCP server %s with its old token", err, step.ServiceID) } // removeUnused removes a server that no space uses, after a check that this From 7cb34f5ae6edfdffbfea5a5f4d258d6a99cc57d0 Mon Sep 17 00:00:00 2001 From: Christina Chu Date: Mon, 26 Oct 2026 10:24:59 -0700 Subject: [PATCH 5/5] fix: do not claim the old MCP server is connected when the check fails Co-Authored-By: Claude Opus 5.5 --- internal/awsdevops/setup.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/internal/awsdevops/setup.go b/internal/awsdevops/setup.go index 18e79ed02..e0cc40922 100644 --- a/internal/awsdevops/setup.go +++ b/internal/awsdevops/setup.go @@ -1288,12 +1288,15 @@ func leaveSharedServer(ctx context.Context, clients Clients, step MCPStep, resul err, created, removeErr, ) } - logf("Removed the new MCP server (%s), because the agent space still uses MCP server %s", created, step.ServiceID) 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) }