I Tried Connecting GitHub, Slack, and Google Calendar to an AI Agent Using User-Delegated Authorization (3LO) with Amazon Bedrock AgentCore Gateway

I Tried Connecting GitHub, Slack, and Google Calendar to an AI Agent Using User-Delegated Authorization (3LO) with Amazon Bedrock AgentCore Gateway

I configured user-delegated authorization (3LO) in Amazon Bedrock AgentCore Gateway so an AI agent hosted on AgentCore Runtime can use GitHub, Slack, and Google Calendar.
2026.07.29

This page has been translated by machine translation. View original

Introduction

Hi, I'm Jinno, a supermarket lover from the Consulting Department.
It's midsummer and so hot. To blow away the heat, I've been hooked on buying cheap ice cream at the supermarket.

On a totally different note, this article is entry #6 in Classmethod's volunteer-run "Summer Vacation Independent Research Relay"! It's a series that goes beyond a simple "I tried it": building out a system, verifying behavior not in the docs, and digging into why a design was chosen. So I put real effort into this one!

Motivation

Previously, I wrote an article about implementing user-delegated authorization (3LO) with Amazon Bedrock AgentCore Identity so an agent could access Google Drive.

https://dev.classmethod.jp/articles/amazon-bedrock-agentcore-identity-3lo-google-drive/

In that article, although the agent itself ran on AgentCore Runtime, the server receiving the OAuth callback was FastAPI on my local PC, and the token for Session Binding was handed over via an environment variable. I prioritized understanding the mechanism and mixed in local pieces, so it wasn't very practical...

At the end of that article I wrote that I wanted to implement the authentication flow seamlessly entirely in the cloud, so this time I'm collecting on that homework (very summer-vacation-like)!!

So that handing over a single URL completes everything from login to authorization, I host the frontend quickly with Amplify. And, getting greedy, I connected three services (GitHub, Slack, and Google Calendar) to a single Gateway, configured with user delegation as the AgentCore Gateway outbound authentication!

I imagine the 3LO-with-Gateway case is often hard to approach, so I hope this serves as a sample for everyone.

To show an example of the finished product first: you ask a question about GitHub, complete authorization, and the agent resumes processing and returns a list of repositories.

GitHub authorization link and answer

This is the GitHub example, but for Slack and Google Calendar too, once you complete authorization the agent resumes processing and returns the result.

The full code is published on GitHub. In this article I've trimmed some details for explanation, so please refer to it as needed!

https://github.com/yuu551/bedrock-agentcore-3lo-gateway

Recap of the previous article (the cast of 3LO)

I'll leave details to the previous article, but here's a quick recap of the players when implementing 3LO with AgentCore Identity. This time the Gateway joins them.

Term Role
Credential Provider Connection settings for an external service. Registers the client ID and secret
Token Vault A vault that safely stores users' access tokens. Tokens are distinguished by the combination of user × workload × Provider
Session Binding After OAuth completes, the process of tying that authorization to the specific user in the Token Vault
Gateway An entry point that converts existing APIs and MCP servers into MCP tools for agents. 3LO can be configured as outbound authentication

The key point of the 3LO flow is Session Binding. When the user completes authorization on the external service, AgentCore Identity redirects to the application's callback screen with a session_id. Unless you tie this session_id to which user the authorization belonged to, no token is saved in the Token Vault and the agent can never obtain it.

Last time I did this tying on a local FastAPI server, but this time I make it serverless with API Gateway + Lambda + DynamoDB.

Architecture this time

Here is the overall picture as a diagram.

Architecture diagram

Component Service used Role
Frontend AWS Amplify Hosting (React SPA) Chat UI, OAuth callback screen, and pre-connection settings panel
User authentication Amazon Cognito (Amplify Auth) Login to the app. The access token is also used to call Runtime and Gateway
Agent AgentCore Runtime + Strands Agents Agent that calls the Gateway's MCP tools
Tool platform AgentCore Gateway Relays three targets and attaches tokens via outbound authentication (3LO)
Conversation memory AgentCore Memory Keeps conversation history per conversation UUID
Authorization AgentCore Identity Credential Provider per service and Token Vault
Session Binding API API Gateway + Lambda + DynamoDB Records authorization flows and completes Session Binding

The Gateway targets are the following three.

Target Connection method Destination
GitHub MCP server target (static tool schema) GitHub official remote MCP server
Slack MCP server target (static tool schema) Slack official remote MCP server
Google Calendar OpenAPI target Google Calendar API (REST)

Some of you may be thinking: wait, doesn't AgentCore Gateway have a built-in template for Slack Web?
Indeed, with built-in templates you can easily add targets from the console.

However, as of writing there are no templates for GitHub and Google Calendar, and the docs say the outbound authentication of the Slack template is API key based.

https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-target-integrations.html

In the spirit of independent research, I wanted to line up all three services with per-user 3LO and also verify connections to the official MCP servers for GitHub and Slack, so I chose MCP server targets for Slack as well instead of the template!

The processing flow as a sequence diagram is below. The flow is the same for every service: the first tool call returns an authorization URL (URL elicitation), and after the user's authorization and Session Binding, a retry resumes processing.

What a long sequence... it makes you go "ugh..."
Let's unravel it!

Authorization is independent per service. Ask about GitHub and you get a GitHub authorization link; ask about the calendar and you get a Google one. Once each is authorized, the token is stored in the Token Vault, and from then on answers come back immediately without authorization.

Also, the end user's JWT is passed as-is for authentication from the agent to the Gateway. The Token Vault identifies users based on the Gateway's inbound JWT, so if the agent used its own M2M token here, all users' tokens would be tied to a single ID and user delegation would become difficult.

Acquiring, storing, and attaching tokens all happens between the Gateway and the Token Vault, so external service tokens appear in neither the agent code nor the frontend. I'll dig into this a bit more in the discussion in the latter half.

Prerequisites

The environment this time is as follows.

Item Value
Region us-east-1 (N. Virginia)
Python 3.12
Node.js 24.x
Package management uv (Python) / pnpm (Node.js)
Agent framework Strands Agents 1.45.0 + MCP Python SDK 1.28.1
AgentCore SDK bedrock-agentcore 1.15.1 or later
Model Claude Haiku 4.5
Frontend React (Vite) + AWS Amplify Gen 2
IaC aws-cdk-lib 2.261.0 or later (using the aws_bedrockagentcore module)

Since the goal is verification and the main point is connecting the agent to tools, I chose Haiku.

As preparation, you need a GitHub account, a Slack workspace where you have permission to install Apps, and a GCP project where you can create OAuth clients.

Build

The overall flow is the following five steps. I leave the agent and frontend code to the repository and focus on 3LO and the targets!

  1. Create OAuth apps on each service
  2. Register client secrets in Secrets Manager
  3. Implement the agent (3LO authorization hook + Memory integration)
  4. Define the Gateway, targets, and Memory in backend.ts
  5. Deploy and register callback URLs

Create OAuth apps on each service

GitHub OAuth App

Create it from GitHub's Settings → Developer settings → OAuth Apps.

The Authorization callback URL can be a placeholder (it gets replaced in step 5). After creation, note the Client ID and Client Secret.

Slack App

Create it with From scratch at https://api.slack.com/apps.
Note that the Slack MCP server feature is available only to Marketplace-published apps or internal apps. This time I created an internal app for my own workspace.

  1. Under OAuth & Permissions, add channels:history / channels:read / search:read.public / users:read to User Token Scopes (not Bot Token Scopes)
  2. Add just one scope, users:read, to Bot Token Scopes as well to create a bot user
  3. Enable MCP server access on the App Assistant page in the app settings
  4. Note the Client ID and Client Secret from Basic Information

The bot user in step 2 isn't actually used. The official docs don't say it's required, but in my verification environment (as of July 2026), without a bot user the authorization screen gave the error doesn't have a bot user to install. If you get the same error, suspect step 2.

Google OAuth client

Enable the Google Calendar API in the GCP console and configure the OAuth consent screen.
From Credentials, create an OAuth client of the web application type and note the Client ID and Client Secret.

https://dev.classmethod.jp/articles/amazon-bedrock-agentcore-identity-3lo-google-drive/

Register client secrets in Secrets Manager

The Credential Providers are created with CDK, so register the secrets in Secrets Manager first to avoid hard-coding them.
All three services are registered in the same format.

Command
aws secretsmanager create-secret \
  --name github-agent/oauth-client-secret \
  --secret-string '{"client_secret": "<GitHubのClient Secret>"}' \
  --region us-east-1
# Same for slack-agent/oauth-client-secret and google-agent/oauth-client-secret

The Credential Provider settings reference this secret as an EXTERNAL source.

Implement the agent (3LO authorization hook)

From the agent's point of view, the Gateway behaves as an MCP server with Bearer authentication. With Strands' standard MCP integration, you just connect to the Gateway with the user's JWT forwarded to the Runtime!

agent/main.py (excerpt)
gateway = MCPClient(
    lambda: streamablehttp_client(
        GATEWAY_URL, headers={"Authorization": f"Bearer {bearer_token}"}
    )
)

with gateway:
    tools = gateway.list_tools_sync()

    agent = Agent(
        model=MODEL_ID,
        tools=tools,
        system_prompt=SYSTEM_PROMPT,
        hooks=[GatewayAuthHook(event_queue)],
        session_manager=session_manager,
        agent_id="default",
    )

However, 3LO needs one extra trick around waiting for authorization.

If you call a tool on the first request while the Token Vault has no token for the user, the Gateway returns a JSON-RPC error (code -32042) whose data contains the authorization URL. On the application side, you notify the frontend of this authorization URL and retry until authorization completes.

For this cross-tool post-processing I use Strands Hooks: AfterToolCallEvent is called every time a tool execution finishes, and setting event.retry = True instructs it to re-run the same tool.

agent/gateway_auth.py(抜粋)
class GatewayAuthHook(HookProvider):

    def __init__(self, event_queue: asyncio.Queue):
        self._event_queue = event_queue
        self._notified_providers: set[str] = set()
        self._deadlines: dict[str, float] = {}

    def register_hooks(self, registry: HookRegistry) -> None:
        registry.add_callback(AfterToolCallEvent, self._on_after_tool_call)

    async def _on_after_tool_call(self, event: AfterToolCallEvent) -> None:
        tool_name = event.tool_use.get("name", "") if event.tool_use else ""
        provider = provider_from_tool_name(tool_name)
        auth_url = extract_auth_url(event.result)

        if auth_url is None:
            # 認可待ちだったproviderのツールが成功したら接続完了を通知
            if (
                provider
                and provider in self._notified_providers
                and _result_status(event.result) == "success"
            ):
                await self._event_queue.put({
                    "type": "connection_status",
                    "provider": provider,
                    "status": "connected",
                })
                self._deadlines.pop(provider, None)
            return

        # providerが特定できない場合も認可自体は進める
        key = provider or f"unknown:{tool_name}"

        if key not in self._deadlines:
            self._deadlines[key] = time.monotonic() + AUTH_DEADLINE_SECONDS
        if time.monotonic() > self._deadlines[key]:
            # タイムアウト: エラーを通知してリトライをやめる
            error_event = {
                "type": "error",
                "scope": "chat",
                "code": "authorization_timeout",
                "data": "認可の待機時間を超えました。もう一度お試しください。",
            }
            if provider:
                error_event["provider"] = provider
            await self._event_queue.put(error_event)
            self._deadlines.pop(key, None)
            return

        if key not in self._notified_providers:
            payload = {
                "type": "auth_required",
                "auth_url": auth_url,
            }
            if provider:
                payload["provider"] = provider
            await self._event_queue.put(payload)
            self._notified_providers.add(key)

        await asyncio.sleep(AUTH_POLL_INTERVAL)
        event.retry = True  # 結果を破棄して同じツールを再実行する

The provider is identified from the tool name prefix (githubmcp___ / slackmcp___ / googlecal___), and notifying the authorization URL, notifying connection completion (connection_status: connected), and timing out at a 5-minute deadline are handled in common across providers. There's no need to implement per-service OAuth handling in the agent.

When adding a service, only three things are configured individually: the prefix mapping table for the connection panel, the read-only tool used to check the connection, and the system prompt.

This 5-second polling isn't ideal. If there were a push-type API that notifies when a token is stored in the Token Vault, we could retry immediately, but none exists at present, so even if authorization has completed you wait up to 5 seconds until the next poll... so the experience is a bit sluggish.

Session Binding API (Lambda + DynamoDB)

The idea is the same as the previous FastAPI version, but this time I made it serverless with Lambda + DynamoDB!
The API consists of two endpoints.

Note that if you use the Consent Portal, you don't need to build this API yourself (see the note at the top).

amplify/functions/session-binding/handler.ts(抜粋)
// session URIはBearer相当のため、テーブルにはSHA-256ハッシュだけを保存
const flowKeyOf = (value: string) =>
  createHash('sha256').update(value).digest('hex');

// POST /auth/pending: 認可URLのrequest_uriをフロー識別子にPENDINGレコードを登録
if (event.rawPath === '/auth/pending') {
  const { flow_id: flowId, provider } = JSON.parse(event.body ?? '{}');
  if (typeof flowId !== 'string' || flowId.length === 0 || flowId.length > 2048) {
    return json(400, { error: 'flow_id is required' });
  }

  const hashedFlowId = flowKeyOf(flowId);
  try {
    await ddb.send(
      new PutCommand({
        TableName: TABLE_NAME,
        Item: {
          userId,
          flowId: hashedFlowId,
          ...(typeof provider === 'string' ? { provider } : {}),
          status: 'PENDING',
          createdAt: new Date().toISOString(),
          ttl: Math.floor(Date.now() / 1000) + 900, // 15分で失効
        },
        // COMPLETED済みレコードをPENDINGへ上書きして二重Bindingを許さない
        ConditionExpression:
          'attribute_not_exists(userId) AND attribute_not_exists(flowId)',
      })
    );
  } catch (e) {
    if (!isConditionalFailure(e)) throw e;

    // 既存レコードを照合し、期限内のPENDINGなら200、
    // 完了済みまたは期限切れなら409を返す(詳細は実装を参照)
  }
  return json(200, { status: 'ok' });
}

// POST /auth/complete: コールバック後にsession_idとユーザーを紐付け
if (event.rawPath === '/auth/complete') {
  const { session_id: sessionId } = JSON.parse(event.body ?? '{}');

  // コールバックのsession_idは認可URLのrequest_uriと同じURNなので、
  // ハッシュが一致するレコードだけが開始済みフローとして照合できる
  const flowId = flowKeyOf(sessionId);

  // PENDINGでなければ拒否(ワンタイム遷移)
  await ddb.send(
    new UpdateCommand({
      TableName: TABLE_NAME,
      Key: { userId, flowId },
      UpdateExpression: 'SET #st = :completed, boundAt = :now',
      ConditionExpression: '#st = :pending AND #ttl > :nowEpoch',
      ExpressionAttributeNames: { '#st': 'status', '#ttl': 'ttl' },
      ExpressionAttributeValues: {
        ':completed': 'COMPLETED',
        ':pending': 'PENDING',
        ':now': new Date().toISOString(),
        ':nowEpoch': Math.floor(Date.now() / 1000),
      },
    })
  );

  // Token Vaultにトークンを紐付ける。失敗時は条件付き更新でPENDINGへロールバック
  await agentcore.send(
    new CompleteResourceTokenAuthCommand({
      sessionUri: sessionId,
      userIdentifier: { userToken: rawToken },
    })
  );
  return json(200, { status: 'bound' });
}

The frontend registers a PENDING record before showing the authorization link, and completion requests without prior registration are not accepted. State transitions are enforced with ConditionExpression to be a one-time PENDING → COMPLETED, and attribute_not_exists is also added on the registration side to prevent overwriting completed flows. The rollback on failure is also conditional: it reverts to PENDING only records that it itself set to COMPLETED. Abandoned flows automatically expire after 15 minutes via TTL.

The key is a composite of userId + flowId, and flowId is the SHA-256 hash of the authorization URL's request_uri. The callback's session_id is the same URN as request_uri, so computing the same hash lets you complete only the matching record. For another flow or a third party's session_id, no such record exists, so it is rejected. I hash it so that a Bearer-equivalent value isn't left in plaintext in the table.

For userIdentifier of CompleteResourceTokenAuthCommand, pass the user's JWT. The Token Vault then ties the token it had temporarily stored under the session_id to the user of that JWT.

Define the Gateway and targets in backend.ts

The Gateway itself is an MCP-protocol entry point with Cognito as the JWT authorizer.

In this sample, SupportedVersions specifies 2025-11-25. As of writing, the MCP protocol versions the Gateway supports are 2026-07-28 / 2025-11-25 / 2025-06-18 / 2025-03-26 (a new version came out recently!!), and the elicitation mechanism that returns the 3LO authorization URL to the client is a spec introduced in 2025-11-25!

https://modelcontextprotocol.io/specification/2025-11-25/changelog

GitHub (MCP server target + static tool schema)

The target is GitHub's official remote MCP server.

By default, for an MCP server target, the Gateway calls tools/list on the MCP server at creation time and caches the tool list as a catalog (Implicit Synchronization).

For a 3LO target, this call itself requires the user's access token, and since nobody has authorized at deployment time, it can't be prepared. As a result, the CreateGatewayTarget response returns an authorization URL for the administrator, and the target stops at CREATE_PENDING_AUTH (awaiting authorization). During this time updates, deletions, and resyncs are not accepted either, and even after the CloudFormation deployment completes, the target doesn't become READY. Having an administrator approve from the console on every deployment is difficult if you want to deploy in one shot.

So this time I use the approach of passing the tool definitions statically via mcpToolSchema. It doesn't call tools/list upstream and caches the given schema as is, so authorization at creation time becomes unnecessary and the target becomes READY when the deployment completes.

The official blog also recommends this approach for cases where no human can intervene at creation/update time (with steps using the GitHub MCP server as the subject).

https://aws.amazon.com/blogs/machine-learning/connecting-mcp-servers-to-amazon-bedrock-agentcore-gateway-using-authorization-code-flow/

https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-target-MCPservers.html

This isn't necessarily the right answer, but I'll try this approach here.

amplify/backend.ts (GitHub target)
new CfnResource(stack, 'GitHubMcpTarget', {
  type: 'AWS::BedrockAgentCore::GatewayTarget',
  properties: {
    Name: 'githubmcp',
    GatewayIdentifier: gateway.ref,
    TargetConfiguration: {
      Mcp: {
        McpServer: {
          Endpoint: 'https://api.githubcopilot.com/mcp/',
          McpToolSchema: {
            InlinePayload: mcpToolsSchema, // contents of github-mcp-tools.json
          },
        },
      },
    },
    CredentialProviderConfigurations: [{
      CredentialProviderType: 'OAUTH',
      CredentialProvider: {
        OauthCredentialProvider: {
          ProviderArn: credentialProvider.getAtt('CredentialProviderArn').toString(),
          Scopes: ['repo', 'read:user'],
          GrantType: 'AUTHORIZATION_CODE',
          DefaultReturnUrl: callbackUrl,
        },
      },
    }],
  },
});

Specifying AUTHORIZATION_CODE for GrantType makes it 3LO (user delegation). On the Credential Provider side, the built-in GithubOauth2 vendor can be used as is.

For the tool definitions, I narrowed the tools published by the GitHub MCP server (44 as of July 2026) down to six read-only ones.

The static setup has downsides: it doesn't automatically follow upstream tool definition changes. SynchronizeGatewayTargets also can't be called while a static schema is configured, so when tools are updated you re-run the script and swap the schema. I accepted this maintenance cost for one-shot deployment, but if you have many tools, manually resolving CREATE_PENDING_AUTH might be easier (though even then, resyncing on changes also causes an authorization wait).

One more point: the tools/list response may have wording in descriptions that depends on the context at retrieval time, such as the authenticated user's ID or whether semantic search is available. Making that static as is would mislead other users or expose personal information, so this time I sanitize the descriptions before using them.

Slack (MCP server target + CustomOauth2)

Slack's official remote MCP server (mcp.slack.com/mcp) is connected with the same static tool schema approach. The target definition is almost the same as GitHub's, so I'll skip it and introduce what's specific to Slack.

The Slack MCP server can only be called with a user token (xoxp-). However, AgentCore Identity's built-in SlackOauth2 vendor uses the standard oauth.v2.access endpoint, so a bot token (xoxb-) gets stored in the Token Vault. The authorization flow completes normally, yet only the tool call is rejected with Authorization error, which made for a confusing failure (I'll introduce the vended logs that were handy for isolating it in the appendix).

After isolating the cause, I arrived at an approach of using the CustomOauth2 vendor to explicitly specify Slack's user-flow-specific endpoints.

amplify/backend.ts (Credential Provider for Slack)
const slackCredentialProvider = new CfnResource(stack, 'SlackCredentialProvider', {
  type: 'AWS::BedrockAgentCore::OAuth2CredentialProvider',
  properties: {
    Name: `slack-user-provider-${suffix}`,
    CredentialProviderVendor: 'CustomOauth2',
    Oauth2ProviderConfigInput: {
      CustomOauth2ProviderConfig: {
        ClientId: SLACK_CLIENT_ID,
        ClientSecretSource: 'EXTERNAL',
        ClientSecretConfig: {
          SecretId: SLACK_SECRET_NAME,
          JsonKey: 'client_secret',
        },
        OauthDiscovery: {
          AuthorizationServerMetadata: {
            Issuer: 'https://slack.com',
            AuthorizationEndpoint: 'https://slack.com/oauth/v2_user/authorize',
            TokenEndpoint: 'https://slack.com/api/oauth.v2.user.access',
            ResponseTypes: ['code'],
          },
        },
      },
    },
  },
});

oauth.v2.user.access is Slack's MCP-oriented endpoint that returns a user token in standard OAuth format. With this, the correct user token goes into the Token Vault and tool calls worked!

Google Calendar (OpenAPI target)

Google Calendar has no generally available official remote MCP server, so I use the Gateway's OpenAPI target. This turns a REST API directly into MCP tools from an OpenAPI definition, which you could call the Gateway's original main use. Even for SaaS without an MCP server, as long as it has a REST API you can connect with the same 3LO pattern, and the agent can call it as a tool like googlecal___listEvents.

I hand-wrote the OpenAPI definition for just three read-only Calendar API operations (list calendars, list events, get event).
There are tools that auto-generate from the Discovery document, but the Gateway can't use schema references via $ref, and the response nesting was too deep to pass validation. Hand-writing is fine while operations are few, but maintaining the definition would become tedious as endpoints grow to include write operations.

amplify/google-calendar-openapi.json (excerpt)
{
  "openapi": "3.0.3",
  "servers": [{ "url": "https://www.googleapis.com/calendar/v3" }],
  "paths": {
    "/calendars/{calendarId}/events": {
      "get": {
        "operationId": "listEvents",
        "description": "指定カレンダーの予定一覧を取得する。timeMin/timeMaxで期間を絞る(RFC3339形式)。ユーザー自身の予定は calendarId='primary' を使う。",
        ...
      }
    }
  }
}

The key points of the target definition are that TargetConfiguration becomes OpenApiSchema, and that CustomParameters is passed in the OAuth settings.

amplify/backend.ts (Google Calendar target)
new CfnResource(stack, 'GoogleCalendarTarget', {
  type: 'AWS::BedrockAgentCore::GatewayTarget',
  properties: {
    Name: 'googlecal',
    GatewayIdentifier: gateway.ref,
    TargetConfiguration: {
      Mcp: {
        OpenApiSchema: {
          InlinePayload: googleCalendarSchema, // contents of the OpenAPI definition
        },
      },
    },
    CredentialProviderConfigurations: [{
      CredentialProviderType: 'OAUTH',
      CredentialProvider: {
        OauthCredentialProvider: {
          ProviderArn: googleCredentialProvider.getAtt('CredentialProviderArn').toString(),
          Scopes: ['https://www.googleapis.com/auth/calendar.readonly'],
          GrantType: 'AUTHORIZATION_CODE',
          DefaultReturnUrl: callbackUrl,
          // Required to obtain a Google refresh token
          CustomParameters: {
            access_type: 'offline',
            prompt: 'consent',
          },
        },
      },
    }],
  },
});

Google access tokens expire after one hour. The Token Vault refreshes them automatically with the refresh token, and the CustomParameters above request its issuance.

https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/identity-authentication.html

On the Credential Provider side, the built-in GoogleOauth2 vendor could be used as is!

Deploy and register callback URLs

Client IDs are not committed and are passed via environment variables, so with sandbox you can deploy as follows.

Command
GITHUB_CLIENT_ID=xxx SLACK_CLIENT_ID=xxx GOOGLE_CLIENT_ID=xxx pnpm ampx sandbox

Deploying to Amplify Hosting also requires no code changes. backend.ts determines the Hosting environment from the build environment variables (AWS_BRANCH/AWS_APP_ID) and automatically switches the callback URL to https://<branch>.<appId>.amplifyapp.com/callback. Connect the repository to Hosting and set the same three Client IDs in the console's environment variables, and the build runs (the build settings are in the repository's amplify.yml). I verified operation this time in this Hosting environment.

When the deployment completes, the callback URLs are output to amplify_outputs.json. For Hosting, you can download it from "Deployed backend resources" in the console.

amplify_outputs.json (excerpt)
{
  "custom": {
    "githubCallbackUrl": "https://...",
    "slackCallbackUrl": "https://...",
    "googleCallbackUrl": "https://..."
  }
}

Set each URL as follows: GitHub as the OAuth App's Authorization callback URL, Slack as the Redirect URLs under OAuth & Permissions, and GCP as the authorized redirect URI of the OAuth client.

Verification

Let's actually try it! Access the Amplify URL, sign up and log in, and talk to it from the chat screen.

First, GitHub. Send "Tell me my repositories" and an authorization link appears at the time of the tool call. Opening the link takes you to GitHub's authorization screen, and after approval the callback tab closes automatically and the retry succeeds in the original chat. As shown in the finished product at the top, the agent resumed processing and returned the repository list.

GitHub authorization link and answer

Slack follows the same flow. Choose a workspace from the authorization link and approve, and message search results came back.

Slack authorization link and search results

Google Calendar is the same. Since it's in test mode an unverified-app warning appears, but you can get through by continuing.

Google authorization screen

After approval, the Calendar API was called via the OpenAPI target and events came back. In the connection settings panel on the right, all three services show as "Connected".

Google Calendar events answer and connection settings panel

Once authorized, the token is stored in the Token Vault, so from then on it works with the MCP server and answers without any authorization link!

Security considerations for production use

By leaving 3LO to the Gateway, external service tokens show up in fewer places. Acquisition, storage, and attachment all happen between the Gateway and the Token Vault, and tokens no longer appear in the agent code or frontend, which I think is a nice point!
Also, since everything goes through the Gateway, there are consolidation benefits such as using Policy to control authorization and choose which tools can be used, and applying guardrails.

For Session Binding, I split the verification of the legitimate user, which was an issue last time, out into Cognito JWT authentication and DynamoDB state management! Since flows are uniquely matched with a flowId that is a hash of request_uri, a session_id the user didn't start themselves can't be completed. Note that the callback screen is implemented to complete automatically on access, so in production it may be good to insert a confirmation button before completion.

All the tools used this time are read-only. System prompt instructions alone are not a sufficient safety boundary for write operations, so I removed send-type tools (such as slack_send_message) along with the OAuth scope (chat:write). Eventually I'd like to try write tools too, like posting to Slack or creating calendar events, and in that case I want to verify only the ones actually needed, together with user confirmation before execution and guardrails.

There are also some loose settings because of the demo purpose (please bear with me...).
The Session Binding API's CORS is *, the Gateway's Identity-related IAM is Resource: *, and ExceptionLevel is left at DEBUG (a setting that returns detailed errors to the client). The mapping between conversation UUIDs and users is also not validated server-side, so these are points I'd revisit if this were made production-ready.

Conclusion

Including Session Binding, which I'd compromised on locally last time, I ran the entire 3LO flow serverlessly and consolidated three external services into a single Gateway!

Being able to choose between an MCP server target when an official MCP server exists and an OpenAPI target when it doesn't was also fun to explore while building the sample! Personally, my summer homework is done and I feel refreshed!

It's rough in places, but I hope it's a little helpful!
Please feel free to send feedback or feature requests as Issues!

That was entry #6 of the "Summer Vacation Independent Research Relay": "I tried connecting GitHub, Slack, and Google Calendar to an AI agent using user-delegated authorization (3LO) with Amazon Bedrock AgentCore Gateway".

The next entry is planned to be Nayuta's entry on "Chronos-2 × Snowflake". Look forward to it!!

Appendix

Comparison with the @requires_access_token approach

A comparison between the previous approach, where the agent handles tokens directly, and this approach, which leaves it to the Gateway's outbound authentication.

Aspect @requires_access_token approach Gateway outbound authentication approach
Where tokens are visible Passed to the agent's code Contained within the Gateway and Token Vault
Calling external APIs The agent implements it directly The Gateway turns existing MCP servers and OpenAPI schemas into tools
Waiting for authorization to complete SDK has built-in polling Retry via a hook
Conversation memory Self-implemented AgentCore Memory + Session Manager
Expanding to multiple services Implement tools per service Authorization handling is shared. Tool selection, connection check, and UI metadata are added

For a small setup completed with a single agent, the previous approach is simpler, but I think the Gateway approach suits cases where you want to reuse tools across multiple agents or isolate tokens from application code!

About Google's official Workspace MCP servers

In fact, Google has also started publishing official remote MCP servers (Developer Preview). Calendar, Gmail, Drive, Chat, Docs, Sheets, Slides, and People each have a dedicated endpoint (for example, Calendar is calendarmcp.googleapis.com/mcp/v1). Authentication uses an OAuth 2.0 web application type client.

https://developers.google.com/workspace/guides/configure-mcp-servers

It looks like a setup that could be connected as an AgentCore Gateway MCP server target, but I haven't verified it this time. Depending on your organization's API controls and OAuth policies, administrator-side settings may be needed. If you can't connect, check the administrator policies and OAuth logs.

Adding another service (Gmail example)

I'm also leaving the steps for when you want to integrate a new service. The approach splits in two depending on whether an official MCP server exists.

If there is an official MCP server, use the same MCP server target approach as GitHub and Slack. For Gmail, Google's official Workspace MCP server (Developer Preview) has a dedicated endpoint. To try connecting, add an entry for the target server to SERVERS in scripts/fetch_mcp_tools.py, generate the static schema, and add the target.

The OAuth client and Credential Provider configuration are the same as for Google Calendar.

If there is no official MCP server, use the same OpenAPI target approach as Google Calendar. Hand-write only the operations you want in the OpenAPI definition and add the target. Anything with a REST API, like the Gmail API, can be connected this way.

With either approach, the places to change are the following five.

  1. Create an OAuth app on the service side and register the Client Secret in Secrets Manager in JSON format
  2. Add the Credential Provider and target to backend.ts, and register the issued callback URL on the service side
  3. Add the prefix mapping to TOOL_PREFIX_TO_PROVIDER in gateway_auth.py, and a read-only tool for connection checks to PROVIDER_PROBES in connections.py
  4. Add to the system prompt in main.py how to use the new service's tools (extracting it into a skill is also an option)
  5. Add the new service to ProviderId in the frontend's types/runtime.ts and to the display info in connectionState.ts

The authorization hook itself is a provider-common mechanism and needs no change; adding a service takes only configuration and metadata.

When adding services under the same account, like Google Calendar and Gmail, watch out for scope differences. If you add a required scope, the existing token lacks the permission and re-authorization is needed.

Also, it's tempting to increase the number of tools, but descriptions directly affect the model's tool selection accuracy, so decide according to your use case.

Why I chose Amplify

I chose Amplify Gen 2 this time because it lets me manage Cognito authentication, hosting, and the CDK backend in one project. In particular, it's convenient that defining the Cognito User Pool and User Pool Client takes just a few lines of Amplify Auth.

On the other hand, AgentCore resource definitions are fundamentally unrelated to Amplify and are piggybacking on backend.ts. To avoid circular references caused by Amplify's stack-splitting rules (the auth stack and function stack etc. are separated), I had to be careful about which stack the AgentCore resources are placed in.

In terms of development experience too, the sandbox environment creates all resources including Gateway, Runtime, and CodeBuild, so the first deployment takes over 5 minutes and redeploying also takes a while, which is a bit troublesome.

For production, I think managing the infrastructure with CDK alone without Amplify and delivering the frontend via CloudFront + S3 would be clearer. Since this is for a demo, I prioritized the convenience of having everything from authentication to hosting in one shot!

About developing in the sandbox environment

backend.ts can create all resources including Gateway and Runtime even in sandbox. Resource names get an environment-specific suffix to avoid collisions, and the callback destination points to the local dev server, so you can run the 3LO flow from a local frontend. Only the GitHub OAuth App can register just one callback URL, so if you want 3LO to work in both sandbox and Hosting, use separate OAuth Apps for development.

vended logs are handy for debugging

What was handy for isolating the Slack bot token issue was the Gateway's log delivery (vended logs). Setting ExceptionLevel to DEBUG returns error details to the client, and enabling vended logs in the console records requests and responses between the Gateway and targets in CloudWatch Logs. Thanks to that, I noticed from the Slack MCP server's error response that a bot token was being sent. The space between the Gateway and the target tends to be a black box, so I felt it's good to enable this first when you get stuck!

Deleting resources

Deleting the Amplify app deletes Hosting, Cognito, the Session Binding API, and also the CDK-managed Gateway, targets, Credential Providers, Memory, and Runtime all together. Please delete the three Secrets Manager secrets and each service's OAuth app manually.

References

I had relied on this a lot before as well, and this blog taught me how the mechanism works...!!
Thank you so much!

https://qiita.com/icoxfog417/items/4f90fb5a62e1bafb1bfb

Share this article