airbyte_ops_mcp.mcp.human_in_the_loop
MCP tools for human-in-the-loop workflows: escalation to a human, team-roster lookup, and Slack newsletter posting.
MCP reference
MCP primitives registered by the human_in_the_loop module of the airbyte-internal-ops server: 5 tool(s), 0 prompt(s), 0 resource(s).
Tools (5)
escalate_to_human
Escalate to a human or Slack usergroup via Slack.
Posts a formatted message to the #human-in-the-loop Slack channel, tagging the specified person(s) or usergroup(s). The message includes clickable buttons for the Devin session, PR, and issue links when provided, plus any additional freeform action buttons.
The Slack message is sent by a GitHub Actions workflow so that Slack credentials are never exposed to the calling agent. The workflow resolves person identifiers (email, GitHub handle, or Slack ID) to Slack user IDs using the internal team roster. S-prefixed Slack usergroup IDs bypass roster resolution and render as usergroup mentions.
Use this tool when you need human input, approval, or help that you cannot resolve on your own.
Parameters:
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
target_person |
string |
yes | — | Primary person to notify. Accepts an email address (e.g. 'aj@airbyte.io'), a GitHub handle prefixed with @ (e.g. '@aaronsteers'), a Slack user ID (e.g. 'U05AKF1BCC9'), or a Slack usergroup ID (e.g. 'S0BKR63VAN5' for @oc-internal-ai). Plain usergroup handles, S-prefixed IDs, and pasted Slack subteam mentions all work; the ID form is the most precise. |
message |
string |
yes | — | The message body to deliver to the human. Format using Slack mrkdwn: bold, _italic_, code, code blocks, > blockquotes, - bullet lists, and |
agent_session_url |
string |
yes | — | Your agent session URL so the human can view the full context. Use the session URL from your system prompt. |
cc |
array<string> | null |
no | null |
Optional list of additional people or Slack usergroups to tag on the message. Each entry uses the same identifier format as target_person. Plain usergroup handles, S-prefixed IDs, and pasted Slack subteam mentions all work; the ID form (e.g. 'S0BKR63VAN5' for @oc-internal-ai) is the most precise. |
pr_url |
string | null |
no | null |
Optional URL to a related pull request for the 'View PR' button. |
issue_url |
string | null |
no | null |
Optional URL to a related GitHub issue for the 'View Issue' button. |
additional_actions |
object | null |
no | null |
Optional dictionary of label -> URL pairs for extra action buttons. Example: {'Start Workflow': 'https://github.com/...actions/...'}. |
approval_requested |
boolean |
no | false |
Set to True to add 'Approve' and 'Reject' buttons that post back to the Slack app. Each button includes a confirmation dialog (if approval_request_summary is provided). When either button is clicked, both buttons morph into non-interactive status text (e.g. ':white_check_mark: Approved by @user' or ':x: Rejected by @user'). |
approval_request_summary |
string | null |
no | null |
Short description of what the user is approving, shown in a Slack confirmation dialog before the Approve button fires. Rendered as a blockquote. MUST be at most 280 characters; over-limit or unbalanced-backtick inputs are rejected at call time. Keep it to the minimum info the approver needs to identify what they are approving. Example: 'Pinning source-hubspot prerelease 4.5.3-preview to workspace for testing'. |
approval_request_detail_url |
string | null |
no | null |
Optional URL where the reviewer can read full details of what they are being asked to approve. Rendered as a 'View Details' button in the Slack message. |
connector_name |
string | null |
no | null |
Optional connector name to display prominently in the Slack message. For example, when combined with request_type='action', the header may be rendered as '🔧 Action Requested — source-salesloft'. If request_type is omitted, the header remains the generic '🙋 Human-in-the-loop request' and the connector name is still included for additional context. Always provide this when the escalation is about a specific connector. |
request_type |
enum("action", "review", "input", "guidance", "approval", "blocked") | null |
no | null |
Type of escalation request. Controls the Slack message header emoji and label. Accepted values: 'action' (🔧 Action Requested), 'review' (👀 Review Requested), 'input' (❓ Input Needed), 'guidance' (🧭 Guidance Needed), 'approval' (✅ Approval Requested), 'blocked' (🚫 Still Blocked). When omitted, defaults to the generic 'Human-in-the-loop request' header. |
Show input JSON schema
{
"additionalProperties": false,
"properties": {
"target_person": {
"description": "Primary person to notify. Accepts an email address (e.g. 'aj@airbyte.io'), a GitHub handle prefixed with @ (e.g. '@aaronsteers'), a Slack user ID (e.g. 'U05AKF1BCC9'), or a Slack usergroup ID (e.g. 'S0BKR63VAN5' for @oc-internal-ai). Plain usergroup handles, S-prefixed IDs, and pasted Slack subteam mentions all work; the ID form is the most precise.",
"type": "string"
},
"message": {
"description": "The message body to deliver to the human. Format using Slack mrkdwn: *bold*, _italic_, `code`, ```code blocks```, > blockquotes, - bullet lists, and <url|label> links. Should clearly explain what you need help with or what decision is required. MUST be at most 3000 characters; over-limit inputs are rejected at call time. For longer content, move detail behind approval_request_detail_url or split into multiple escalations.",
"type": "string"
},
"agent_session_url": {
"description": "Your agent session URL so the human can view the full context. Use the session URL from your system prompt.",
"type": "string"
},
"cc": {
"anyOf": [
{
"items": {
"type": "string"
},
"type": "array"
},
{
"type": "null"
}
],
"default": null,
"description": "Optional list of additional people or Slack usergroups to tag on the message. Each entry uses the same identifier format as target_person. Plain usergroup handles, S-prefixed IDs, and pasted Slack subteam mentions all work; the ID form (e.g. 'S0BKR63VAN5' for @oc-internal-ai) is the most precise."
},
"pr_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Optional URL to a related pull request for the 'View PR' button."
},
"issue_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Optional URL to a related GitHub issue for the 'View Issue' button."
},
"additional_actions": {
"anyOf": [
{
"additionalProperties": {
"type": "string"
},
"type": "object"
},
{
"type": "null"
}
],
"default": null,
"description": "Optional dictionary of label -> URL pairs for extra action buttons. Example: {'Start Workflow': 'https://github.com/...actions/...'}."
},
"approval_requested": {
"default": false,
"description": "Set to True to add 'Approve' and 'Reject' buttons that post back to the Slack app. Each button includes a confirmation dialog (if approval_request_summary is provided). When either button is clicked, both buttons morph into non-interactive status text (e.g. ':white_check_mark: Approved by @user' or ':x: Rejected by @user').",
"type": "boolean"
},
"approval_request_summary": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Short description of what the user is approving, shown in a Slack confirmation dialog before the Approve button fires. Rendered as a blockquote. MUST be at most 280 characters; over-limit or unbalanced-backtick inputs are rejected at call time. Keep it to the minimum info the approver needs to identify what they are approving. Example: 'Pinning source-hubspot prerelease 4.5.3-preview to workspace for testing'."
},
"approval_request_detail_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Optional URL where the reviewer can read full details of what they are being asked to approve. Rendered as a 'View Details' button in the Slack message."
},
"connector_name": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Optional connector name to display prominently in the Slack message. For example, when combined with request_type='action', the header may be rendered as '\ud83d\udd27 Action Requested \u2014 source-salesloft'. If request_type is omitted, the header remains the generic '\ud83d\ude4b Human-in-the-loop request' and the connector name is still included for additional context. Always provide this when the escalation is about a specific connector."
},
"request_type": {
"anyOf": [
{
"description": "Type of escalation request, controlling the Slack header emoji and label.",
"enum": [
"action",
"review",
"input",
"guidance",
"approval",
"blocked"
],
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Type of escalation request. Controls the Slack message header emoji and label. Accepted values: 'action' (\ud83d\udd27 Action Requested), 'review' (\ud83d\udc40 Review Requested), 'input' (\u2753 Input Needed), 'guidance' (\ud83e\udded Guidance Needed), 'approval' (\u2705 Approval Requested), 'blocked' (\ud83d\udeab Still Blocked). When omitted, defaults to the generic 'Human-in-the-loop request' header."
}
},
"required": [
"target_person",
"message",
"agent_session_url"
],
"type": "object"
}
Show output JSON schema
{
"description": "Response from the human-in-the-loop escalation tool.",
"properties": {
"success": {
"description": "Whether the workflow was triggered successfully",
"type": "boolean"
},
"message": {
"description": "Human-readable status message",
"type": "string"
},
"slack_channel_url": {
"default": "https://airbytehq-team.slack.com/archives/C0AEXV81Q7N",
"description": "Direct URL to the #human-in-the-loop Slack channel",
"type": "string"
},
"workflow_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "URL to view the GitHub Actions workflow file"
},
"run_id": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"default": null,
"description": "GitHub Actions workflow run ID"
},
"run_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Direct URL to the GitHub Actions workflow run"
}
},
"required": [
"success",
"message"
],
"type": "object"
}
list_team_roster
List the full Airbyte internal team roster.
Returns all members from the daily-generated roster artifact. The roster is sorted by Slack display name for easy scanning. Use lookup_person for targeted searches instead of scanning the full list.
Parameters:
_No parameters._
Show input JSON schema
{
"additionalProperties": false,
"properties": {},
"type": "object"
}
Show output JSON schema
{
"description": "Response listing the full internal team roster.",
"properties": {
"total_members": {
"description": "Total number of members in the roster",
"type": "integer"
},
"members": {
"description": "All person records in the roster",
"items": {
"description": "A person in the internal team roster.",
"properties": {
"slack_id": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Slack user ID"
},
"slack_display_name": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Slack display name"
},
"slack_email": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Email address from Slack profile"
},
"github_id": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"default": null,
"description": "GitHub numeric user ID"
},
"github_handle": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "GitHub username"
},
"github_public_email": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Public email from GitHub profile"
}
},
"type": "object"
},
"type": "array"
}
},
"required": [
"total_members",
"members"
],
"type": "object"
}
lookup_person
Look up a person in the Airbyte internal team roster.
Searches the daily-generated roster artifact by any field value. The roster is built from Slack and GitHub org membership data, cross-referenced by email address.
Use this to find someone's Slack ID for messaging, GitHub handle for code review, or to cross-reference identities across platforms. Slack usergroup handles and names are searchable too; use the returned usergroup ID for the most precise team reference.
Parameters:
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
query |
string |
yes | — | Search query to match against any field: email address, Slack display name, Slack user ID, GitHub handle, or GitHub user ID. Case-insensitive partial matching for strings, exact match for numeric IDs. |
Show input JSON schema
{
"additionalProperties": false,
"properties": {
"query": {
"description": "Search query to match against any field: email address, Slack display name, Slack user ID, GitHub handle, or GitHub user ID. Case-insensitive partial matching for strings, exact match for numeric IDs.",
"type": "string"
}
},
"required": [
"query"
],
"type": "object"
}
Show output JSON schema
{
"description": "Response from a people lookup query.",
"properties": {
"query": {
"description": "The search query that was used",
"type": "string"
},
"total_matches": {
"description": "Number of matching person records; usergroups are reported separately",
"type": "integer"
},
"matches": {
"description": "Matching person records",
"items": {
"description": "A person in the internal team roster.",
"properties": {
"slack_id": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Slack user ID"
},
"slack_display_name": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Slack display name"
},
"slack_email": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Email address from Slack profile"
},
"github_id": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"default": null,
"description": "GitHub numeric user ID"
},
"github_handle": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "GitHub username"
},
"github_public_email": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Public email from GitHub profile"
}
},
"type": "object"
},
"type": "array"
},
"usergroup_matches": {
"description": "Matching Slack usergroups",
"items": {
"description": "A Slack usergroup and its mention metadata.",
"properties": {
"id": {
"description": "Slack usergroup ID used in <!subteam^ID|@handle>",
"type": "string"
},
"handle": {
"description": "Slack usergroup handle without the leading @",
"type": "string"
},
"name": {
"description": "Slack usergroup display name",
"type": "string"
},
"description": {
"description": "Slack usergroup description",
"type": "string"
},
"user_count": {
"description": "Number of members in the usergroup",
"type": "integer"
}
},
"required": [
"id",
"handle",
"name",
"description",
"user_count"
],
"type": "object"
},
"type": "array"
}
},
"required": [
"query",
"total_matches",
"matches"
],
"type": "object"
}
lookup_slack_usergroup
Resolve Slack usergroups to IDs for usergroup mentions.
Pass a handle or name to resolve oncall aliases such as @oc-apis, or
pass an S-prefixed usergroup ID for the corresponding handle and name.
Results include the ID and metadata needed for the
<!subteam^ID|@alias> mention syntax used by Slack messages.
Parameters:
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
id_or_handle |
string |
yes | — | Required Slack usergroup handle/name or S-prefixed usergroup ID. Handle/name matching is case-insensitive and partial; a leading @ is ignored. S-prefixed IDs are matched exactly. |
Show input JSON schema
{
"additionalProperties": false,
"properties": {
"id_or_handle": {
"description": "Required Slack usergroup handle/name or S-prefixed usergroup ID. Handle/name matching is case-insensitive and partial; a leading @ is ignored. S-prefixed IDs are matched exactly.",
"type": "string"
}
},
"required": [
"id_or_handle"
],
"type": "object"
}
Show output JSON schema
{
"description": "Response from a Slack usergroup lookup.",
"properties": {
"id_or_handle": {
"description": "The usergroup ID or handle/name lookup",
"type": "string"
},
"total_matches": {
"description": "Number of matching usergroups",
"type": "integer"
},
"matches": {
"description": "Matching Slack usergroups",
"items": {
"description": "A Slack usergroup and its mention metadata.",
"properties": {
"id": {
"description": "Slack usergroup ID used in <!subteam^ID|@handle>",
"type": "string"
},
"handle": {
"description": "Slack usergroup handle without the leading @",
"type": "string"
},
"name": {
"description": "Slack usergroup display name",
"type": "string"
},
"description": {
"description": "Slack usergroup description",
"type": "string"
},
"user_count": {
"description": "Number of members in the usergroup",
"type": "integer"
}
},
"required": [
"id",
"handle",
"name",
"description",
"user_count"
],
"type": "object"
},
"type": "array"
}
},
"required": [
"id_or_handle",
"total_matches",
"matches"
],
"type": "object"
}
post_slack_newsletter
Post a formatted newsletter digest to a Slack channel.
Converts Slack mrkdwn text into Block Kit blocks locally (with
validation), then dispatches them to a GitHub Actions workflow for
posting. The workflow receives finished Block Kit JSON — it does
not perform any markdown conversion.
When agent_session_url is provided, appends a linked session footer.
Dry-run modes:
local: returns blocks JSON for local rendering — no workflow triggeredslack_test_channel: posts to a test channel for formatting verification
Parameters:
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
message_text |
string |
yes | — | The formatted message to post, using Slack mrkdwn syntax: bold, _italic_, code, code blocks, > blockquotes, - bullet lists, and |
newsletter_name |
enum("DR", "Internal AI", "AJ", "AJ WIP Tracker") |
yes | — | Name of the newsletter to post to. Determines which Slack channel receives the message. DR and Internal AI both post to #daily-newsletters; AJ posts to #aj-release-notes; AJ WIP Tracker posts to #aj-wip-tracker. Ignored when dry_run is 'slack_test_channel'. |
dry_run |
string |
no | "off" |
Controls dry-run behaviour. 'off' (default): post to the real channel. 'local': build blocks locally and return blocks JSON plus a Block Kit Builder URL — no workflow is triggered. 'slack_test_channel': trigger the workflow but post to a test channel instead of the production newsletter channel. |
agent_session_url |
string | null |
no | null |
URL of the Devin session posting this newsletter, e.g. 'https://app.devin.ai/sessions/<32-hex-id>'. When provided, a small grey footer line 'Posted by |
Show input JSON schema
{
"additionalProperties": false,
"properties": {
"message_text": {
"description": "The formatted message to post, using Slack mrkdwn syntax: *bold*, _italic_, `code`, ```code blocks```, > blockquotes, - bullet lists, and <url|label> links. Use ## for section headers (translated to Block Kit header blocks) and ### for sub-headers (translated to bold text). Double newlines (\\n\\n) split the text into separate visual sections in the Slack message. Do NOT include markdown tables \u2014 they will be rejected.",
"type": "string"
},
"newsletter_name": {
"description": "Name of the newsletter to post to. Determines which Slack channel receives the message. DR and Internal AI both post to #daily-newsletters; AJ posts to #aj-release-notes; AJ WIP Tracker posts to #aj-wip-tracker. Ignored when dry_run is 'slack_test_channel'.",
"enum": [
"DR",
"Internal AI",
"AJ",
"AJ WIP Tracker"
],
"type": "string"
},
"dry_run": {
"default": "off",
"description": "Controls dry-run behaviour. 'off' (default): post to the real channel. 'local': build blocks locally and return blocks JSON plus a Block Kit Builder URL \u2014 no workflow is triggered. 'slack_test_channel': trigger the workflow but post to a test channel instead of the production newsletter channel.",
"type": "string"
},
"agent_session_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "URL of the Devin session posting this newsletter, e.g. 'https://app.devin.ai/sessions/<32-hex-id>'. When provided, a small grey footer line 'Posted by <Session Name> :devin:' linking to the session is appended automatically. Always pass your own session URL when posting from a Devin session."
}
},
"required": [
"message_text",
"newsletter_name"
],
"type": "object"
}
Show output JSON schema
{
"description": "Response from the post_slack_newsletter tool.",
"properties": {
"success": {
"description": "Whether the operation completed successfully",
"type": "boolean"
},
"message": {
"description": "Human-readable status message",
"type": "string"
},
"blocks_json": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Serialised JSON array of Block Kit blocks. Populated in 'local' dry-run mode so the agent can render or inspect the blocks directly."
},
"workflow_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "URL to view the GitHub Actions workflow file"
},
"run_id": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"default": null,
"description": "GitHub Actions workflow run ID"
},
"channel_name": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Human-readable Slack channel name (e.g. '#daily-newsletters')"
},
"run_url": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "Direct URL to the GitHub Actions workflow run"
}
},
"required": [
"success",
"message"
],
"type": "object"
}
1# Copyright (c) 2025 Airbyte, Inc., all rights reserved. 2"""MCP tools for human-in-the-loop workflows: escalation to a human, team-roster lookup, and Slack newsletter posting. 3 4## MCP reference 5 6.. include:: ../../../docs/mcp-generated/human_in_the_loop.md 7 :start-line: 2 8""" 9 10from __future__ import annotations 11 12__all__: list[str] = [] 13 14import json 15import logging 16from enum import Enum, StrEnum 17from typing import Annotated, Literal 18 19from fastmcp import FastMCP 20from fastmcp_extensions import mcp_tool, register_mcp_tools 21from pydantic import BaseModel, Field 22 23from airbyte_ops_mcp.devin_api import extract_session_id 24from airbyte_ops_mcp.github_actions import ( 25 WorkflowDispatchResult, 26 WorkflowRunStatus, 27 resolve_default_workflow_branch, 28 trigger_workflow_dispatch, 29 wait_for_workflow_completion, 30) 31from airbyte_ops_mcp.github_api import resolve_ci_trigger_github_token 32from airbyte_ops_mcp.human_in_the_loop import ( 33 HITL_REPO_NAME, 34 HITL_REPO_OWNER, 35 HITL_SLACK_CHANNEL_URL, 36 dispatch_escalation, 37) 38from airbyte_ops_mcp.internal_team_roster import fetch_roster, search_roster 39from airbyte_ops_mcp.session_namer import generate_friendly_name 40from airbyte_ops_mcp.slack_api import lookup_slack_usergroup as find_slack_usergroups 41from airbyte_ops_mcp.slack_ops.blocks import ( 42 _MAX_BLOCKS, 43 build_blocks, 44 build_context_footer, 45 validate_message, 46) 47 48 49class PersonRecord(BaseModel): 50 """A person in the internal team roster.""" 51 52 slack_id: str | None = Field(default=None, description="Slack user ID") 53 slack_display_name: str | None = Field( 54 default=None, description="Slack display name" 55 ) 56 slack_email: str | None = Field( 57 default=None, description="Email address from Slack profile" 58 ) 59 github_id: int | None = Field(default=None, description="GitHub numeric user ID") 60 github_handle: str | None = Field(default=None, description="GitHub username") 61 github_public_email: str | None = Field( 62 default=None, description="Public email from GitHub profile" 63 ) 64 65 66class SlackUsergroupRecord(BaseModel): 67 """A Slack usergroup and its mention metadata.""" 68 69 id: str = Field(description="Slack usergroup ID used in <!subteam^ID|@handle>") 70 handle: str = Field(description="Slack usergroup handle without the leading @") 71 name: str = Field(description="Slack usergroup display name") 72 description: str = Field(description="Slack usergroup description") 73 user_count: int = Field(description="Number of members in the usergroup") 74 75 76class PeopleLookupResponse(BaseModel): 77 """Response from a people lookup query.""" 78 79 query: str = Field(description="The search query that was used") 80 total_matches: int = Field( 81 description="Number of matching person records; usergroups are reported separately" 82 ) 83 matches: list[PersonRecord] = Field(description="Matching person records") 84 usergroup_matches: list[SlackUsergroupRecord] = Field( 85 default_factory=list, 86 description="Matching Slack usergroups", 87 ) 88 89 90class RosterListResponse(BaseModel): 91 """Response listing the full internal team roster.""" 92 93 total_members: int = Field(description="Total number of members in the roster") 94 members: list[PersonRecord] = Field(description="All person records in the roster") 95 96 97class SlackUsergroupLookupResponse(BaseModel): 98 """Response from a Slack usergroup lookup.""" 99 100 id_or_handle: str = Field(description="The usergroup ID or handle/name lookup") 101 total_matches: int = Field(description="Number of matching usergroups") 102 matches: list[SlackUsergroupRecord] = Field(description="Matching Slack usergroups") 103 104 105@mcp_tool( 106 read_only=True, 107 idempotent=True, 108) 109def lookup_person( 110 query: Annotated[ 111 str, 112 Field( 113 description=( 114 "Search query to match against any field: email address, " 115 "Slack display name, Slack user ID, GitHub handle, or GitHub user ID. " 116 "Case-insensitive partial matching for strings, exact match for numeric IDs." 117 ) 118 ), 119 ], 120) -> PeopleLookupResponse: 121 """Look up a person in the Airbyte internal team roster. 122 123 Searches the daily-generated roster artifact by any field value. 124 The roster is built from Slack and GitHub org membership data, 125 cross-referenced by email address. 126 127 Use this to find someone's Slack ID for messaging, GitHub handle 128 for code review, or to cross-reference identities across platforms. 129 Slack usergroup handles and names are searchable too; use the returned 130 usergroup ID for the most precise team reference. 131 """ 132 roster = fetch_roster() 133 matches = search_roster(roster, query) 134 try: 135 usergroup_matches = find_slack_usergroups(query) 136 except Exception as exc: 137 logger.warning("Could not look up Slack usergroups for %s: %s", query, exc) 138 usergroup_matches = [] 139 return PeopleLookupResponse( 140 query=query, 141 total_matches=len(matches), 142 matches=[PersonRecord.model_validate(person) for person in matches], 143 usergroup_matches=[ 144 SlackUsergroupRecord( 145 id=usergroup.id, 146 handle=usergroup.handle, 147 name=usergroup.name, 148 description=usergroup.description, 149 user_count=usergroup.user_count, 150 ) 151 for usergroup in usergroup_matches 152 ], 153 ) 154 155 156@mcp_tool( 157 read_only=True, 158 idempotent=True, 159) 160def list_team_roster() -> RosterListResponse: 161 """List the full Airbyte internal team roster. 162 163 Returns all members from the daily-generated roster artifact. 164 The roster is sorted by Slack display name for easy scanning. 165 Use lookup_person for targeted searches instead of scanning the full list. 166 """ 167 roster = fetch_roster() 168 return RosterListResponse( 169 total_members=len(roster), 170 members=[PersonRecord.model_validate(person) for person in roster], 171 ) 172 173 174@mcp_tool( 175 read_only=True, 176 idempotent=True, 177) 178def lookup_slack_usergroup( 179 id_or_handle: Annotated[ 180 str, 181 Field( 182 description=( 183 "Required Slack usergroup handle/name or S-prefixed usergroup ID. " 184 "Handle/name matching is " 185 "case-insensitive and partial; a leading @ is ignored. " 186 "S-prefixed IDs are matched exactly." 187 ) 188 ), 189 ], 190) -> SlackUsergroupLookupResponse: 191 """Resolve Slack usergroups to IDs for usergroup mentions. 192 193 Pass a handle or name to resolve oncall aliases such as `@oc-apis`, or 194 pass an S-prefixed usergroup ID for the corresponding handle and name. 195 Results include the ID and metadata needed for the 196 `<!subteam^ID|@alias>` mention syntax used by Slack messages. 197 """ 198 usergroups = find_slack_usergroups(id_or_handle) 199 return SlackUsergroupLookupResponse( 200 id_or_handle=id_or_handle, 201 total_matches=len(usergroups), 202 matches=[ 203 SlackUsergroupRecord( 204 id=usergroup.id, 205 handle=usergroup.handle, 206 name=usergroup.name, 207 description=usergroup.description, 208 user_count=usergroup.user_count, 209 ) 210 for usergroup in usergroups 211 ], 212 ) 213 214 215class RequestType(StrEnum): 216 """Type of escalation request, controlling the Slack header emoji and label.""" 217 218 ACTION = "action" 219 REVIEW = "review" 220 INPUT = "input" 221 GUIDANCE = "guidance" 222 APPROVAL = "approval" 223 BLOCKED = "blocked" 224 225 226_REQUEST_TYPE_HEADERS: dict[RequestType, tuple[str, str]] = { 227 RequestType.ACTION: ("🔧", "Action Requested"), 228 RequestType.REVIEW: ("👀", "Review Requested"), 229 RequestType.INPUT: ("❓", "Input Needed"), 230 RequestType.GUIDANCE: ("🧭", "Guidance Needed"), 231 RequestType.APPROVAL: ("✅", "Approval Requested"), 232 RequestType.BLOCKED: ("🚫", "Still Blocked"), 233} 234 235 236def _format_failure_details(run_status: WorkflowRunStatus) -> str: 237 """Build a human-readable summary of failed jobs from a workflow run.""" 238 if not run_status.jobs: 239 return "" 240 failed_jobs = [j for j in run_status.jobs if j.conclusion == "failure"] 241 if not failed_jobs: 242 return "" 243 job_summaries = [f" - {j.name} (job_id={j.job_id})" for j in failed_jobs] 244 return " Failed jobs:\n" + "\n".join(job_summaries) 245 246 247class EscalateToHumanResponse(BaseModel): 248 """Response from the human-in-the-loop escalation tool.""" 249 250 success: bool = Field(description="Whether the workflow was triggered successfully") 251 message: str = Field(description="Human-readable status message") 252 slack_channel_url: str = Field( 253 default=HITL_SLACK_CHANNEL_URL, 254 description="Direct URL to the #human-in-the-loop Slack channel", 255 ) 256 workflow_url: str | None = Field( 257 default=None, 258 description="URL to view the GitHub Actions workflow file", 259 ) 260 run_id: int | None = Field( 261 default=None, 262 description="GitHub Actions workflow run ID", 263 ) 264 run_url: str | None = Field( 265 default=None, 266 description="Direct URL to the GitHub Actions workflow run", 267 ) 268 269 270@mcp_tool( 271 read_only=False, 272 idempotent=False, 273 open_world=True, 274) 275def escalate_to_human( 276 target_person: Annotated[ 277 str, 278 "Primary person to notify. Accepts an email address (e.g. 'aj@airbyte.io'), " 279 "a GitHub handle prefixed with @ (e.g. '@aaronsteers'), " 280 "a Slack user ID (e.g. 'U05AKF1BCC9'), or a Slack usergroup ID " 281 "(e.g. 'S0BKR63VAN5' for @oc-internal-ai). Plain usergroup handles, " 282 "S-prefixed IDs, and pasted Slack subteam mentions all work; the ID " 283 "form is the most precise.", 284 ], 285 message: Annotated[ 286 str, 287 "The message body to deliver to the human. Format using Slack mrkdwn: " 288 "*bold*, _italic_, `code`, ```code blocks```, > blockquotes, " 289 "- bullet lists, and <url|label> links. Should clearly explain " 290 "what you need help with or what decision is required. " 291 "MUST be at most 3000 characters; over-limit inputs are rejected " 292 "at call time. For longer content, move detail behind " 293 "approval_request_detail_url or split into multiple escalations.", 294 ], 295 agent_session_url: Annotated[ 296 str, 297 "Your agent session URL so the human can view the full context. " 298 "Use the session URL from your system prompt.", 299 ], 300 cc: Annotated[ 301 list[str] | None, 302 "Optional list of additional people or Slack usergroups to tag on the " 303 "message. Each entry uses the same identifier format as target_person. " 304 "Plain usergroup handles, S-prefixed IDs, and pasted Slack subteam " 305 "mentions all work; the ID form (e.g. 'S0BKR63VAN5' for " 306 "@oc-internal-ai) is the most precise.", 307 ] = None, 308 pr_url: Annotated[ 309 str | None, 310 "Optional URL to a related pull request for the 'View PR' button.", 311 ] = None, 312 issue_url: Annotated[ 313 str | None, 314 "Optional URL to a related GitHub issue for the 'View Issue' button.", 315 ] = None, 316 additional_actions: Annotated[ 317 dict[str, str] | None, 318 "Optional dictionary of label -> URL pairs for extra action buttons. " 319 "Example: {'Start Workflow': 'https://github.com/...actions/...'}.", 320 ] = None, 321 approval_requested: Annotated[ 322 bool, 323 "Set to True to add 'Approve' and 'Reject' buttons that post back to the Slack app. " 324 "Each button includes a confirmation dialog (if approval_request_summary is provided). " 325 "When either button is clicked, both buttons morph into non-interactive status text " 326 "(e.g. ':white_check_mark: Approved by @user' or ':x: Rejected by @user').", 327 ] = False, 328 approval_request_summary: Annotated[ 329 str | None, 330 "Short description of what the user is approving, shown in a Slack " 331 "confirmation dialog before the Approve button fires. Rendered as a " 332 "blockquote. MUST be at most 280 characters; over-limit or " 333 "unbalanced-backtick inputs are rejected at call time. Keep it to the " 334 "minimum info the approver needs to identify what they are approving. " 335 "Example: 'Pinning source-hubspot prerelease 4.5.3-preview to workspace for testing'.", 336 ] = None, 337 approval_request_detail_url: Annotated[ 338 str | None, 339 "Optional URL where the reviewer can read full details of what they are " 340 "being asked to approve. Rendered as a 'View Details' button in the Slack message.", 341 ] = None, 342 connector_name: Annotated[ 343 str | None, 344 "Optional connector name to display prominently in the Slack message. " 345 "For example, when combined with request_type='action', the header may be " 346 "rendered as '🔧 Action Requested — source-salesloft'. If request_type is omitted, " 347 "the header remains the generic '🙋 Human-in-the-loop request' and the connector " 348 "name is still included for additional context. Always provide this when the " 349 "escalation is about a specific connector.", 350 ] = None, 351 request_type: Annotated[ 352 RequestType | None, 353 "Type of escalation request. Controls the Slack message header emoji and label. " 354 "Accepted values: 'action' (🔧 Action Requested), " 355 "'review' (👀 Review Requested), 'input' (❓ Input Needed), " 356 "'guidance' (🧭 Guidance Needed), 'approval' (✅ Approval Requested), " 357 "'blocked' (🚫 Still Blocked). " 358 "When omitted, defaults to the generic 'Human-in-the-loop request' header.", 359 ] = None, 360) -> EscalateToHumanResponse: 361 """Escalate to a human or Slack usergroup via Slack. 362 363 Posts a formatted message to the #human-in-the-loop Slack channel, 364 tagging the specified person(s) or usergroup(s). The message includes 365 clickable buttons for the Devin session, PR, and issue links when provided, 366 plus any additional freeform action buttons. 367 368 The Slack message is sent by a GitHub Actions workflow so that Slack 369 credentials are never exposed to the calling agent. The workflow 370 resolves person identifiers (email, GitHub handle, or Slack ID) to Slack 371 user IDs using the internal team roster. S-prefixed Slack usergroup IDs 372 bypass roster resolution and render as usergroup mentions. 373 374 Use this tool when you need human input, approval, or help that you 375 cannot resolve on your own. 376 """ 377 # Resolve request_type to header_emoji and header_label 378 header_emoji: str | None = None 379 header_label: str | None = None 380 if request_type is not None: 381 header_emoji, header_label = _REQUEST_TYPE_HEADERS[request_type] 382 383 result = dispatch_escalation( 384 target_person=target_person, 385 message=message, 386 agent_session_url=agent_session_url, 387 cc=cc, 388 pr_url=pr_url, 389 issue_url=issue_url, 390 additional_actions=additional_actions, 391 approval_requested=approval_requested, 392 approval_request_summary=approval_request_summary, 393 approval_request_detail_url=approval_request_detail_url, 394 connector_name=connector_name, 395 header_emoji=header_emoji, 396 header_label=header_label, 397 ) 398 399 view_url = result.run_url or result.workflow_url 400 401 if result.run_id is None: 402 return EscalateToHumanResponse( 403 success=True, 404 message=( 405 f"Escalation sent to '{target_person}' via #human-in-the-loop " 406 f"({HITL_SLACK_CHANNEL_URL}). " 407 f"View progress at: {view_url}" 408 ), 409 workflow_url=result.workflow_url, 410 run_id=result.run_id, 411 run_url=result.run_url, 412 ) 413 414 run_status = wait_for_workflow_completion( 415 owner=HITL_REPO_OWNER, 416 repo=HITL_REPO_NAME, 417 run_id=result.run_id, 418 token=resolve_ci_trigger_github_token(), 419 poll_interval_seconds=5.0, 420 max_wait_seconds=120.0, 421 ) 422 423 if run_status.failed: 424 return EscalateToHumanResponse( 425 success=False, 426 message=( 427 f"Escalation workflow FAILED (conclusion={run_status.conclusion}) " 428 f"— the Slack message was NOT posted. " 429 f"Run: {run_status.run_url or view_url}" 430 f"{_format_failure_details(run_status)}" 431 ), 432 workflow_url=result.workflow_url, 433 run_id=result.run_id, 434 run_url=run_status.run_url or result.run_url, 435 ) 436 437 if not run_status.succeeded: 438 return EscalateToHumanResponse( 439 success=True, 440 message=( 441 f"Escalation run dispatched to '{target_person}' via " 442 f"#human-in-the-loop ({HITL_SLACK_CHANNEL_URL}) and is still " 443 f"in progress (status={run_status.status}, " 444 f"conclusion={run_status.conclusion}). " 445 f"Run: {run_status.run_url or view_url}. " 446 "Confirm delivery with `check_ci_workflow_status`." 447 ), 448 workflow_url=result.workflow_url, 449 run_id=result.run_id, 450 run_url=run_status.run_url or result.run_url, 451 ) 452 453 return EscalateToHumanResponse( 454 success=True, 455 message=( 456 f"Escalation sent to '{target_person}' via #human-in-the-loop " 457 f"({HITL_SLACK_CHANNEL_URL}). " 458 f"View progress at: {view_url}" 459 ), 460 workflow_url=result.workflow_url, 461 run_id=result.run_id, 462 run_url=result.run_url, 463 ) 464 465 466logger = logging.getLogger(__name__) 467 468_NEWSLETTER_CHANNELS: dict[str, tuple[str, str]] = { 469 "DR": ("C0AH48172M6", "#daily-newsletters"), 470 "Internal AI": ("C0AH48172M6", "#daily-newsletters"), 471 "AJ": ("C0BLUPJ0X0R", "#aj-release-notes"), 472 "AJ WIP Tracker": ("C0C2PHD33RN", "#aj-wip-tracker"), 473} 474 475_REPO_OWNER = "airbytehq" 476 477_REPO_NAME = "airbyte-ops-mcp" 478 479_WORKFLOW_FILE = "slack-post-message.yml" 480 481_DEFAULT_BRANCH = "main" 482 483_DRY_RUN_CHANNEL = "C0AEN317Z7T" 484 485 486class DryRunMode(str, Enum): 487 """Controls how dry-run behaves.""" 488 489 off = "off" 490 """Normal mode — post to the real channel.""" 491 492 local = "local" 493 """Local-only preview. Builds Block Kit JSON and returns both the 494 blocks JSON (for agent-side rendering) and a Block Kit Builder URL. 495 No workflow is triggered.""" 496 497 slack_test_channel = "slack_test_channel" 498 """Triggers the real workflow but posts to a test channel instead of 499 the production newsletter channel.""" 500 501 502class PostToSlackChannelResponse(BaseModel): 503 """Response from the post_slack_newsletter tool.""" 504 505 success: bool = Field(description="Whether the operation completed successfully") 506 message: str = Field(description="Human-readable status message") 507 blocks_json: str | None = Field( 508 default=None, 509 description=( 510 "Serialised JSON array of Block Kit blocks. " 511 "Populated in 'local' dry-run mode so the agent can " 512 "render or inspect the blocks directly." 513 ), 514 ) 515 workflow_url: str | None = Field( 516 default=None, 517 description="URL to view the GitHub Actions workflow file", 518 ) 519 run_id: int | None = Field( 520 default=None, 521 description="GitHub Actions workflow run ID", 522 ) 523 channel_name: str | None = Field( 524 default=None, 525 description="Human-readable Slack channel name (e.g. '#daily-newsletters')", 526 ) 527 run_url: str | None = Field( 528 default=None, 529 description="Direct URL to the GitHub Actions workflow run", 530 ) 531 532 533@mcp_tool( 534 read_only=False, 535 idempotent=False, 536 open_world=True, 537) 538def post_slack_newsletter( 539 message_text: Annotated[ 540 str, 541 "The formatted message to post, using Slack mrkdwn syntax: " 542 "*bold*, _italic_, `code`, ```code blocks```, > blockquotes, " 543 "- bullet lists, and <url|label> links. " 544 "Use ## for section headers (translated to Block Kit header blocks) " 545 "and ### for sub-headers (translated to bold text). " 546 "Double newlines (\\n\\n) split the text into separate visual " 547 "sections in the Slack message. " 548 "Do NOT include markdown tables — they will be rejected.", 549 ], 550 newsletter_name: Annotated[ 551 Literal["DR", "Internal AI", "AJ", "AJ WIP Tracker"], 552 "Name of the newsletter to post to. " 553 "Determines which Slack channel receives the message. " 554 "DR and Internal AI both post to #daily-newsletters; AJ posts to " 555 "#aj-release-notes; AJ WIP Tracker posts to #aj-wip-tracker. " 556 "Ignored when dry_run is 'slack_test_channel'.", 557 ], 558 dry_run: Annotated[ 559 str, 560 "Controls dry-run behaviour. " 561 "'off' (default): post to the real channel. " 562 "'local': build blocks locally and return blocks JSON plus a " 563 "Block Kit Builder URL — no workflow is triggered. " 564 "'slack_test_channel': trigger the workflow but post to a test " 565 "channel instead of the production newsletter channel.", 566 ] = "off", 567 agent_session_url: Annotated[ 568 str | None, 569 "URL of the Devin session posting this newsletter, e.g. " 570 "'https://app.devin.ai/sessions/<32-hex-id>'. When provided, a small " 571 "grey footer line 'Posted by <Session Name> :devin:' linking to the " 572 "session is appended automatically. Always pass your own session URL " 573 "when posting from a Devin session.", 574 ] = None, 575) -> PostToSlackChannelResponse: 576 """Post a formatted newsletter digest to a Slack channel. 577 578 Converts Slack mrkdwn text into Block Kit blocks locally (with 579 validation), then dispatches them to a GitHub Actions workflow for 580 posting. The workflow receives finished Block Kit JSON — it does 581 not perform any markdown conversion. 582 When `agent_session_url` is provided, appends a linked session footer. 583 584 Dry-run modes: 585 - `local`: returns blocks JSON for local rendering — no workflow triggered 586 - `slack_test_channel`: posts to a test channel for formatting verification 587 """ 588 try: 589 mode = DryRunMode(dry_run) 590 except ValueError: 591 allowed_values = ", ".join(m.value for m in DryRunMode) 592 return PostToSlackChannelResponse( 593 success=False, 594 message=( 595 f"Invalid dry_run value {dry_run!r}. " 596 f"Allowed values are: {allowed_values}." 597 ), 598 ) 599 600 # --- Validate input --- 601 try: 602 validate_message(message_text) 603 except ValueError as exc: 604 return PostToSlackChannelResponse( 605 success=False, 606 message=str(exc), 607 ) 608 609 # --- Build Block Kit blocks locally --- 610 blocks_dict = build_blocks(message_text) 611 if agent_session_url is not None: 612 try: 613 session_id = extract_session_id(agent_session_url) 614 except ValueError as exc: 615 return PostToSlackChannelResponse( 616 success=False, 617 message=str(exc), 618 ) 619 session_name = generate_friendly_name(session_id) 620 footer = build_context_footer( 621 f"Posted by <https://app.devin.ai/sessions/{session_id}|" 622 f"{session_name}> :devin:" 623 ) 624 if len(blocks_dict) >= _MAX_BLOCKS: 625 blocks_dict = [*blocks_dict[: _MAX_BLOCKS - 1], footer] 626 else: 627 blocks_dict.append(footer) 628 blocks_json = json.dumps(blocks_dict) 629 630 # --- Local mode: return blocks JSON, no dispatch --- 631 if mode is DryRunMode.local: 632 return PostToSlackChannelResponse( 633 success=True, 634 message=( 635 "Local preview generated. Use the blocks_json field to " 636 "render the message locally." 637 ), 638 blocks_json=blocks_json, 639 ) 640 641 # --- Resolve target channel --- 642 if mode is DryRunMode.slack_test_channel: 643 resolved_channel = _DRY_RUN_CHANNEL 644 resolved_channel_name = "#slackbot-testing-channel--ignore-plz" 645 else: 646 resolved_channel, resolved_channel_name = _NEWSLETTER_CHANNELS[newsletter_name] 647 648 resolved_fallback = message_text[:120].replace("\n", " ") 649 650 # --- Dispatch to GitHub Actions --- 651 token = resolve_ci_trigger_github_token() 652 result: WorkflowDispatchResult = trigger_workflow_dispatch( 653 owner=_REPO_OWNER, 654 repo=_REPO_NAME, 655 workflow_file=_WORKFLOW_FILE, 656 ref=resolve_default_workflow_branch(_DEFAULT_BRANCH), 657 inputs={ 658 "channel_id": resolved_channel, 659 "blocks_json": blocks_json, 660 "fallback_text": resolved_fallback, 661 }, 662 token=token, 663 ) 664 665 view_url = result.run_url or result.workflow_url 666 mode_label = ( 667 " (dry run — test channel)" if mode is DryRunMode.slack_test_channel else "" 668 ) 669 670 # --- Guard: if we couldn't discover the run, return early --- 671 if result.run_id is None: 672 return PostToSlackChannelResponse( 673 success=False, 674 message=( 675 f"Workflow dispatched to {resolved_channel_name}{mode_label} " 676 f"but could not discover the run ID to verify completion. " 677 f"Check manually: {view_url}" 678 ), 679 channel_name=resolved_channel_name, 680 workflow_url=result.workflow_url, 681 ) 682 683 # --- Wait for workflow completion and report failures --- 684 run_status: WorkflowRunStatus = wait_for_workflow_completion( 685 owner=_REPO_OWNER, 686 repo=_REPO_NAME, 687 run_id=result.run_id, 688 token=token, 689 poll_interval_seconds=5.0, 690 max_wait_seconds=120.0, 691 ) 692 693 if run_status.failed: 694 failure_details = _format_failure_details(run_status) 695 return PostToSlackChannelResponse( 696 success=False, 697 message=( 698 f"Workflow run FAILED (conclusion={run_status.conclusion}) " 699 f"for {resolved_channel_name}{mode_label}. " 700 f"Run: {run_status.run_url or view_url}" 701 f"{failure_details}" 702 ), 703 channel_name=resolved_channel_name, 704 workflow_url=result.workflow_url, 705 run_id=result.run_id, 706 run_url=run_status.run_url or result.run_url, 707 ) 708 709 if not run_status.succeeded: 710 return PostToSlackChannelResponse( 711 success=False, 712 message=( 713 f"Workflow run did not complete within 120s " 714 f"(status={run_status.status}, " 715 f"conclusion={run_status.conclusion}){mode_label}. " 716 f"Run: {run_status.run_url or view_url}" 717 ), 718 channel_name=resolved_channel_name, 719 workflow_url=result.workflow_url, 720 run_id=result.run_id, 721 run_url=run_status.run_url or result.run_url, 722 ) 723 724 return PostToSlackChannelResponse( 725 success=True, 726 message=( 727 f"Message posted to {resolved_channel_name} " 728 f"({resolved_channel}){mode_label}. " 729 f"Run: {view_url}" 730 ), 731 channel_name=resolved_channel_name, 732 workflow_url=result.workflow_url, 733 run_id=result.run_id, 734 run_url=result.run_url, 735 ) 736 737 738def register_human_in_the_loop_tools(app: FastMCP) -> None: 739 """Register human-in-the-loop tools with the FastMCP app.""" 740 register_mcp_tools(app, mcp_module=__name__)