Engineering

Add GitHub's MCP server to AgentCore Gateway with a read-only token

Part 3 of 5: GitHub's remote MCP server works behind Amazon Bedrock AgentCore Gateway with a fine-grained, read-only token. Two things caught us out: tool lists come in pages, and the gateway invents output schemas that Claude Desktop rejects.

Add GitHub's MCP server to AgentCore Gateway with a read-only token

GitHub’s remote MCP server works behind Amazon Bedrock AgentCore Gateway with a fine-grained, read-only token held in AgentCore Identity. Claude Code and Claude Desktop then reach GitHub through the same gateway as everything else. This guide adds it, checks each step, and fixes the two things that caught us out.

The short version

  • Store the token as an API key credential provider. The gateway adds it as a bearer header.
  • The gateway’s role needs permission to read that credential, or every call fails.
  • tools/list comes in pages of 30. Count tools across every page before deciding something is missing.
  • The gateway adds output schemas to GitHub’s tools that Claude Desktop rejects. A small response interceptor fixes it.
  • A read-only token stops writes, but the write tools are still listed and still cost tokens.

This builds on our AgentCore Gateway guide. You need its gateway, GATEWAY_ID, GW and the shell variables from its first steps. Metomic Boundary, our invented 900-person payments company, wants its engineers to ask Claude about one internal repository.

The AgentCore Gateway series, in order:

  1. Put Claude Code on Bedrock behind your own sign-in
  2. Run Claude Desktop through the same gateway
  3. Add GitHub’s MCP server with a read-only token (this guide)
  4. Give each person their own HubSpot sign-in
  5. Count what the MCP tool definitions cost per model call

Step 1: Which GitHub token do you need?

A fine-grained personal access token, scoped to the repositories Claude should read:

  • Repository access: only select repositories.
  • Permissions: Contents, Issues and Pull requests set to Read-only. GitHub adds Metadata read on its own.
  • Nothing else. No write permissions and no Administration.
  • If your organisation requires approval for fine-grained tokens, it stays pending until an owner approves it.

Copy the token, then save it without it ever appearing on screen:

umask 077; pbpaste > ~/.github-agentcore-pat

Check: ls -l ~/.github-agentcore-pat shows -rw-------.

Step 2: How do you store the token in AgentCore Identity?

An API key credential provider keeps the token in AgentCore’s vault. Read it from the file in Python, so it never appears in your shell history or process list.

# github_credential.py
import boto3, os
c = boto3.client("bedrock-agentcore-control", region_name=os.environ["AWS_REGION"])
p = c.create_api_key_credential_provider(name="boundary-github",
        apiKey=open(os.path.expanduser("~/.github-agentcore-pat")).read().strip())
print(p["credentialProviderArn"])
print(p["apiKeySecretArn"]["secretArn"])

Keep both ARNs it prints. To rotate the token later, call update_api_key_credential_provider with the same name.

Step 3: What must the gateway’s role be allowed to do?

The gateway fetches the key with its own role. Without this policy, the target can’t reach GitHub.

SECRET_ARN=<the secret ARN from step 2>
aws iam put-role-policy --role-name $NAME --policy-name read-target-credentials --policy-document "{
  \"Version\":\"2012-10-17\",\"Statement\":[
   {\"Effect\":\"Allow\",\"Action\":[\"bedrock-agentcore:GetWorkloadAccessToken\",\"bedrock-agentcore:GetWorkloadAccessTokenForJWT\",
     \"bedrock-agentcore:GetWorkloadAccessTokenForUserId\",\"bedrock-agentcore:GetResourceApiKey\",\"bedrock-agentcore:GetResourceOauth2Token\"],
    \"Resource\":\"arn:aws:bedrock-agentcore:$AWS_REGION:$ACCOUNT:*\"},
   {\"Effect\":\"Allow\",\"Action\":\"secretsmanager:GetSecretValue\",\"Resource\":\"$SECRET_ARN\"}]}"

The OAuth actions are there for the HubSpot guide, which reuses this policy.

Step 4: How do you add GitHub as a target?

# github_target.py
import boto3, os
c = boto3.client("bedrock-agentcore-control", region_name=os.environ["AWS_REGION"])
t = c.create_gateway_target(gatewayIdentifier=os.environ["GATEWAY_ID"], name="github",
    targetConfiguration={"mcp": {"mcpServer": {"endpoint": "https://api.githubcopilot.com/mcp/"}}},
    credentialProviderConfigurations=[{"credentialProviderType": "API_KEY", "credentialProvider": {"apiKeyCredentialProvider": {
        "providerArn": os.environ["PROVIDER_ARN"], "credentialLocation": "HEADER",
        "credentialParameterName": "Authorization", "credentialPrefix": "Bearer"}}}])
print(t["targetId"])
PROVIDER_ARN=<the provider ARN from step 2> python3 github_target.py

Check: aws bedrock-agentcore-control list-gateway-targets --gateway-identifier $GATEWAY_ID --query "items[].[name,status]" --output text shows github READY. The gateway lists the server’s tools when the target is created, so READY means that listing worked.

Step 5: How do you count the tools when the list comes in pages?

The gateway returns tools/list 30 tools at a time, with a nextCursor for the next page. This script follows the cursor, counts tools by target, and finds the output schemas that will trouble Desktop.

# list_tools.py: python3 list_tools.py   (needs GW in the environment and a fresh ~/.agentcore-id-token)
import collections, json, os, urllib.request

def rpc(body):
    token = open(os.path.expanduser(os.environ.get("AGENTCORE_TOKEN_FILE", "~/.agentcore-id-token"))).read().strip()
    request = urllib.request.Request(os.environ["GW"] + "/mcp", data=json.dumps(body).encode(), method="POST",
        headers={"authorization": "Bearer " + token, "content-type": "application/json",
                 "accept": "application/json, text/event-stream"})
    text = urllib.request.urlopen(request, timeout=60).read().decode()
    if text.lstrip().startswith(("event:", "data:")):   # a streamed answer: the JSON is on the data lines
        text = "\n".join(line[5:].strip() for line in text.splitlines() if line.startswith("data:"))
    return json.loads(text)

tools, cursor = [], None
while True:
    result = rpc({"jsonrpc": "2.0", "id": len(tools) + 1, "method": "tools/list",
                  "params": {"cursor": cursor} if cursor else {}})["result"]
    tools += result["tools"]
    cursor = result.get("nextCursor")
    if not cursor:
        break

counts = collections.Counter(t["name"].split("___")[0] for t in tools)
odd = [t["name"] for t in tools if isinstance(t.get("outputSchema"), dict) and t["outputSchema"].get("type") != "object"]
print(f"{len(tools)} tools:", dict(counts))
print(f"{len(odd)} with an output schema whose type isn't object:", odd[:5])

Check: you see 'github': 46 beside DeepWiki’s 3. Our first page held only 27 GitHub tools, and we spent a while looking for the rest before we noticed the cursor.

Then call a read tool through the gateway:

curl -s "$GW/mcp" -H "Authorization: Bearer $(cat ~/.agentcore-id-token)" \
  -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"github___list_branches",
       "arguments":{"owner":"metomic-boundary","repo":"payments-core","perPage":2}}}'

Check: the result’s text is a JSON list of branches, each with a name and sha.

Why does Claude Desktop reject the tool list?

Claude Desktop said “Couldn’t reconnect the agentcore connector”, and its log said why:

grep 'custom3p-mcp' ~/Library/Logs/Claude-3p/main.log | grep 'connect failed' | tail -1

The line names Invalid result for tools/list. GitHub’s server sends no output schemas, but the gateway gave several of its tools one anyway. Some were typed ["null", "object"], some ["null", "array"], and some had a oneOf with no type at all. Examples were create_repository, get_team_members and get_file_contents.

The MCP specification says an output schema’s type is "object". Desktop checks that, and one bad schema loses you the whole list. Your list_tools.py output shows how many you have.

How do you fix the output schemas?

An AgentCore gateway can run a Lambda function on each request and response, called an interceptor. This one drops any output schema whose type isn’t "object" from tools/list, and passes everything else through untouched. Without an output schema, a tool is exactly as GitHub described it.

# fix_output_schemas.py
def handler(event, context):
    if "http" in event:  # model calls through an inference target: leave them alone
        return {"interceptorOutputVersion": "1.0", "http": {}}
    mcp = event.get("mcp") or {}
    request = (mcp.get("gatewayRequest") or {}).get("body")
    response = mcp.get("gatewayResponse")
    if response is None:  # the request, before the target is called: pass it on untouched
        return {"interceptorOutputVersion": "1.0", "mcp": {"transformedGatewayRequest": {"body": request}}}
    body = response.get("body")
    if isinstance(request, dict) and request.get("method") == "tools/list" and isinstance(body, dict) and isinstance((body.get("result") or {}).get("tools"), list):
        tools = []
        for tool in body["result"]["tools"]:
            schema = tool.get("outputSchema")
            if isinstance(schema, dict) and schema.get("type") != "object":
                tool = {k: v for k, v in tool.items() if k != "outputSchema"}
            tools.append(tool)
        body = dict(body, result=dict(body["result"], tools=tools))
    # Only statusCode and body: echoing the gateway's headers back makes it answer 500.
    return {"interceptorOutputVersion": "1.0", "mcp": {"transformedGatewayResponse": {"statusCode": response.get("statusCode", 200), "body": body}}}

Deploy it and let the gateway’s role call it:

aws iam create-role --role-name $NAME-schemas --assume-role-policy-document \
  '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name $NAME-schemas --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
sleep 10
zip fix.zip fix_output_schemas.py
aws lambda create-function --function-name $NAME-schemas --runtime python3.13 --architectures arm64 \
  --handler fix_output_schemas.handler --timeout 10 --role arn:aws:iam::$ACCOUNT:role/$NAME-schemas --zip-file fileb://fix.zip
export FN_ARN=$(aws lambda get-function --function-name $NAME-schemas --query Configuration.FunctionArn --output text)
aws iam put-role-policy --role-name $NAME --policy-name invoke-interceptor --policy-document \
  "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"$FN_ARN\"}]}"

Then attach it to the gateway. update_gateway replaces the whole configuration, so this copies every setting the update accepts and changes only the interceptors:

# attach_interceptor.py
import boto3, os
c = boto3.client("bedrock-agentcore-control", region_name=os.environ["AWS_REGION"])
accepted = c.meta.service_model.operation_model("UpdateGateway").input_shape.members
now = c.get_gateway(gatewayIdentifier=os.environ["GATEWAY_ID"])
settings = {k: v for k, v in now.items() if k in accepted}
settings["gatewayIdentifier"] = os.environ["GATEWAY_ID"]
settings["interceptorConfigurations"] = [{"interceptor": {"lambda": {"arn": os.environ["FN_ARN"]}},
                                          "interceptionPoints": ["REQUEST", "RESPONSE"]}]
c.update_gateway(**settings)

Check: run list_tools.py again. The count with an odd output schema is now 0. Quit and reopen Desktop, and its log shows server connected with the full tool count.

A note on what we ran. Our gateway’s interceptor does more than this, and this function is that one part cut out. We tested the cut-down version on sample gateway events, including a real tools/list page’s shape, but not on its own in front of a gateway. We wired ours to both request and response. Response alone should be enough for this job.

Can you send Claude fewer GitHub tools?

You probably should. GitHub’s 46 tool definitions cost 15,177 tokens on every model call, counted with Bedrock’s CountTokens for Claude Haiku 4.5. A read-only token doesn’t help, because GitHub lists its write tools anyway.

GitHub documents two ways to narrow its remote server’s list:

  • Read-only. Add /readonly to the URL, as in https://api.githubcopilot.com/mcp/readonly, to list only read tools.
  • Toolsets. Use https://api.githubcopilot.com/mcp/x/repos for one toolset, such as repos, issues or pull_requests. They combine, as in /mcp/x/issues/readonly.

Both are just a different endpoint on the target, so they need no headers. We haven’t tried them through AgentCore. Read-only won’t fix the output schemas either, because read tools like get_file_contents had them too.

What goes wrong, and what does it mean?

You see Cause
The target doesn’t reach READY Read its statusReasons, and check the role can read the credential (step 3)
Only 27 GitHub tools The first page of tools/list: follow nextCursor
“Couldn’t reconnect the agentcore connector” in Desktop Output schemas whose type isn’t object
500 from the gateway after adding an interceptor The interceptor returned the gateway’s headers. Return only statusCode and body
A write tool fails with a permission error from GitHub What a read-only token should do

What’s still hard?

  • One identity for everyone. Every call reaches GitHub as the token’s owner. GitHub’s audit log can’t tell your engineers apart, so the gateway’s own records have to.
  • The list is the whole server. Every tool definition rides along on every model call, whether Claude needs it or not. Our write-up on tool definitions has the numbers.
  • Outside text. Issues and pull requests are written by people outside your company. Claude reads them as context, which is worth thinking about before you add write access. We’ve written about why the whole conversation matters.
  • The interceptor is yours to run. It’s small, but it’s a Lambda function on every MCP call, with its own logs and failure modes.

What do you have now?

  • GitHub’s MCP server behind your gateway, with a read-only token nobody can copy out of a config file.
  • A script that counts tools properly across pages.
  • Claude Desktop accepting the gateway’s tool list.

Next: each person’s own HubSpot sign-in through the same gateway. A read-only token is a blunt instrument: grading each write by what it actually does, and who is asking, is the job we give our governed MCP gateway. We’re working with a small number of security teams on governing agents’ writes. If you’ve found a cleaner fix for the schemas, tell us.

My calendar is open, book a slot if you want to chat

Frequently asked questions

How does AgentCore Gateway send a GitHub token to GitHub's MCP server?
You store the token in AgentCore Identity as an API key credential provider. The target then names that provider with credentialLocation HEADER, parameter name Authorization and prefix Bearer. The gateway fetches the key and adds the header on every call to api.githubcopilot.com. Your people never see the token, and it never sits in a client's configuration file.
Why does Claude Desktop say it couldn't reconnect the connector after adding GitHub?
The gateway gave several GitHub tools output schemas that GitHub never sent, some typed as null or object, null or array, or with no type at all. The MCP specification says an output schema's type is object, and Claude Desktop rejected the whole tool list over them. Dropping those schemas from tools/list fixed it for us.
Why do I only see 27 of GitHub's tools?
AgentCore Gateway returns tools/list in pages of 30 and gives a nextCursor for the rest. With DeepWiki's three tools first, the first page held only 27 of GitHub's 46. Follow nextCursor until it's gone. The gateway also has a documented disableMcpListToolsPagination setting, which we haven't tried.
Does a read-only token stop Claude using GitHub's write tools?
It stops the writes, not the tools. With our read-only token, GitHub's server still listed its write tools, such as create_repository. A fine-grained token without write permission can't make the change itself. GitHub documents a /readonly path that lists only read tools, which would also shrink what every model call carries. We haven't tried it through the gateway.
Whose identity does GitHub see when Claude calls it through the gateway?
The token owner's, for every person. An API key credential is one shared identity, so GitHub's audit log shows the same account whoever asked Claude. If you need each person's own GitHub identity, use an OAuth credential provider with the authorization code grant instead, as we did for HubSpot.