Skip to content

unblu_mcp

unblu-mcp package.

A model context protocol server for interacting with Unblu deployments.

Modules:

  • cli

Classes:

Functions:

AccountInfo

Bases: _NextSteps

Current Unblu account information.

AvailabilityInfo

Bases: _NextSteps

Agent availability status.

ConfigurationError

Bases: Exception

Raised when there's a configuration or setup error.

This exception is caught by the CLI and displayed as a clean error message without a full traceback, making it easier for users to understand what went wrong.

ConnectionConfig dataclass

ConnectionConfig(
    base_url: str,
    headers: dict[str, str] = dict(),
    auth: Auth | None = None,
    timeout: float = 30.0,
)

Configuration returned by a connection provider.

Attributes:

auth class-attribute instance-attribute

auth: Auth | None = None

Optional httpx auth handler for basic auth, etc.

base_url instance-attribute

base_url: str

The base URL for API requests (e.g., http://localhost:8084/app/rest/v4).

headers class-attribute instance-attribute

headers: dict[str, str] = field(default_factory=dict)

Additional headers to include in all requests (e.g., trusted headers).

timeout class-attribute instance-attribute

timeout: float = 30.0

Request timeout in seconds.

ConnectionProvider

Bases: ABC

Abstract base class for connection providers.

Connection providers handle the complexity of connecting to Unblu deployments in various environments. They can:

  • Start/stop port-forwards or tunnels
  • Manage authentication (API keys, basic auth, trusted headers)
  • Handle environment switching
  • Refresh credentials when needed

Example implementation for Kubernetes:

class K8sConnectionProvider(ConnectionProvider):
    def __init__(self, environment: str = "dev"):
        self.environment = environment
        self._port_forward_process = None

    async def setup(self) -> None:
        # Start kubectl port-forward
        ...

    async def teardown(self) -> None:
        # Stop port-forward
        ...

    def get_config(self) -> ConnectionConfig:
        return ConnectionConfig(
            base_url=f"http://localhost:{self.port}/app/rest/v4",
            headers={
                "x-unblu-trusted-user-id": "superadmin",
                "x-unblu-trusted-user-role": "SUPER_ADMIN",
            },
        )

Methods:

  • ensure_connection

    Ensure the connection is alive, restarting if needed.

  • get_config

    Return the current connection configuration.

  • health_check

    Check if the connection is healthy.

  • setup

    Initialize the connection (start port-forward, refresh auth, etc.).

  • teardown

    Clean up resources (stop port-forward, close connections, etc.).

ensure_connection async

ensure_connection() -> None

Ensure the connection is alive, restarting if needed.

Called before each API request. Override this in providers that need to handle connection recovery (e.g., restarting a dead port-forward).

Default implementation does nothing.

Source code in src/unblu_mcp/_internal/providers.py
77
78
79
80
81
82
83
84
async def ensure_connection(self) -> None:  # noqa: B027
    """Ensure the connection is alive, restarting if needed.

    Called before each API request. Override this in providers that need
    to handle connection recovery (e.g., restarting a dead port-forward).

    Default implementation does nothing.
    """

get_config abstractmethod

get_config() -> ConnectionConfig

Return the current connection configuration.

This is called for each API request, allowing dynamic configuration (e.g., refreshing tokens, switching environments).

Returns:

  • ConnectionConfig

    ConnectionConfig with base_url, headers, auth, and timeout.

Source code in src/unblu_mcp/_internal/providers.py
86
87
88
89
90
91
92
93
94
95
@abstractmethod
def get_config(self) -> ConnectionConfig:
    """Return the current connection configuration.

    This is called for each API request, allowing dynamic configuration
    (e.g., refreshing tokens, switching environments).

    Returns:
        ConnectionConfig with base_url, headers, auth, and timeout.
    """

health_check async

health_check() -> bool

Check if the connection is healthy.

Override this to implement custom health checks (e.g., ping the API).

Returns:

  • bool

    True if the connection is healthy, False otherwise.

Source code in src/unblu_mcp/_internal/providers.py
 97
 98
 99
100
101
102
103
104
105
async def health_check(self) -> bool:  # noqa: PLR6301
    """Check if the connection is healthy.

    Override this to implement custom health checks (e.g., ping the API).

    Returns:
        True if the connection is healthy, False otherwise.
    """
    return True

setup abstractmethod async

setup() -> None

Initialize the connection (start port-forward, refresh auth, etc.).

Called once when the MCP server starts, before any API requests. Should be idempotent - safe to call multiple times.

Source code in src/unblu_mcp/_internal/providers.py
61
62
63
64
65
66
67
@abstractmethod
async def setup(self) -> None:
    """Initialize the connection (start port-forward, refresh auth, etc.).

    Called once when the MCP server starts, before any API requests.
    Should be idempotent - safe to call multiple times.
    """

teardown abstractmethod async

teardown() -> None

Clean up resources (stop port-forward, close connections, etc.).

Called when the MCP server shuts down. Should be safe to call even if setup() was never called.

Source code in src/unblu_mcp/_internal/providers.py
69
70
71
72
73
74
75
@abstractmethod
async def teardown(self) -> None:
    """Clean up resources (stop port-forward, close connections, etc.).

    Called when the MCP server shuts down.
    Should be safe to call even if setup() was never called.
    """

ConversationDetail

Bases: _NextSteps

Full conversation details for debugging.

ConversationPage

Bases: _NextSteps

Paginated list of conversations.

ConversationParticipant

Bases: BaseModel

A participant in a conversation.

ConversationSummary

Bases: BaseModel

Compact conversation info for list results.

DefaultConnectionProvider

DefaultConnectionProvider(
    base_url: str | None = None,
    api_key: str | None = None,
    username: str | None = None,
    password: str | None = None,
    trusted_headers: dict[str, str] | None = None,
)

Bases: ConnectionProvider

Default provider using environment variables.

This is the standard provider for direct connections to Unblu Cloud or self-hosted deployments with direct network access.

Environment variables

UNBLU_BASE_URL: API base URL (default: https://unblu.cloud/app/rest/v4) UNBLU_API_KEY: Bearer token for API key auth UNBLU_USERNAME: Username for basic auth UNBLU_PASSWORD: Password for basic auth UNBLU_TRUSTED_HEADERS: Trusted headers (format: "key:value,key:value")

Methods:

  • ensure_connection

    Ensure the connection is alive, restarting if needed.

  • get_config

    Build config from environment variables and constructor args.

  • health_check

    Check if the connection is healthy.

  • setup

    No setup needed for direct connections.

  • teardown

    No teardown needed for direct connections.

Source code in src/unblu_mcp/_internal/providers.py
122
123
124
125
126
127
128
129
130
131
132
133
134
def __init__(
    self,
    base_url: str | None = None,
    api_key: str | None = None,
    username: str | None = None,
    password: str | None = None,
    trusted_headers: dict[str, str] | None = None,
) -> None:
    self._base_url = base_url
    self._api_key = api_key
    self._username = username
    self._password = password
    self._trusted_headers = trusted_headers

ensure_connection async

ensure_connection() -> None

Ensure the connection is alive, restarting if needed.

Called before each API request. Override this in providers that need to handle connection recovery (e.g., restarting a dead port-forward).

Default implementation does nothing.

Source code in src/unblu_mcp/_internal/providers.py
77
78
79
80
81
82
83
84
async def ensure_connection(self) -> None:  # noqa: B027
    """Ensure the connection is alive, restarting if needed.

    Called before each API request. Override this in providers that need
    to handle connection recovery (e.g., restarting a dead port-forward).

    Default implementation does nothing.
    """

get_config

get_config() -> ConnectionConfig

Build config from environment variables and constructor args.

Source code in src/unblu_mcp/_internal/providers.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def get_config(self) -> ConnectionConfig:
    """Build config from environment variables and constructor args."""
    # Load from environment if not provided
    base_url = self._base_url or os.environ.get("UNBLU_BASE_URL", "https://unblu.cloud/app/rest/v4")
    api_key = self._api_key or os.environ.get("UNBLU_API_KEY")
    username = self._username or os.environ.get("UNBLU_USERNAME")
    password = self._password or os.environ.get("UNBLU_PASSWORD")
    trusted_headers = self._trusted_headers
    if trusted_headers is None:
        trusted_headers = _parse_trusted_headers(os.environ.get("UNBLU_TRUSTED_HEADERS"))

    # Build headers and auth
    headers: dict[str, str] = {}
    auth: httpx.Auth | None = None

    if trusted_headers:
        headers.update(trusted_headers)
    elif api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    elif username and password:
        auth = httpx.BasicAuth(username, password)

    return ConnectionConfig(
        base_url=base_url,
        headers=headers,
        auth=auth,
    )

health_check async

health_check() -> bool

Check if the connection is healthy.

Override this to implement custom health checks (e.g., ping the API).

Returns:

  • bool

    True if the connection is healthy, False otherwise.

Source code in src/unblu_mcp/_internal/providers.py
 97
 98
 99
100
101
102
103
104
105
async def health_check(self) -> bool:  # noqa: PLR6301
    """Check if the connection is healthy.

    Override this to implement custom health checks (e.g., ping the API).

    Returns:
        True if the connection is healthy, False otherwise.
    """
    return True

setup async

setup() -> None

No setup needed for direct connections.

Source code in src/unblu_mcp/_internal/providers.py
136
137
async def setup(self) -> None:
    """No setup needed for direct connections."""

teardown async

teardown() -> None

No teardown needed for direct connections.

Source code in src/unblu_mcp/_internal/providers.py
139
140
async def teardown(self) -> None:
    """No teardown needed for direct connections."""

DeploymentHealthReport

Bases: _NextSteps

Full health report from check_deployment_health().

ExecuteResult

Bases: _NextSteps

Result from execute_operation.

HealthCheck

Bases: BaseModel

Result of a single deployment health sub-check.

K8sConnectionProvider

K8sConnectionProvider(
    environment: str | K8sEnvironmentConfig = "dev",
    trusted_user_id: str = "superadmin",
    trusted_user_role: str = "SUPER_ADMIN",
    environments: dict[str, K8sEnvironmentConfig]
    | None = None,
)

Bases: ConnectionProvider

Connection provider for Kubernetes deployments using port-forwarding.

This provider: - Automatically starts kubectl port-forward on setup - Cleans up the port-forward process on teardown - Configures trusted headers authentication - Supports multiple environments with different ports

Parameters:

  • environment (str | K8sEnvironmentConfig, default: 'dev' ) –

    Environment name (dev, staging, prod) or custom K8sEnvironmentConfig.

  • trusted_user_id (str, default: 'superadmin' ) –

    User ID for trusted headers auth (default: superadmin).

  • trusted_user_role (str, default: 'SUPER_ADMIN' ) –

    User role for trusted headers auth (default: SUPER_ADMIN).

  • environments (dict[str, K8sEnvironmentConfig] | None, default: None ) –

    Custom environment configurations (overrides defaults).

Example

provider = K8sConnectionProvider(environment="dev") await provider.setup() # Starts port-forward config = provider.get_config() # Returns connection config await provider.teardown() # Stops port-forward

Methods:

  • ensure_connection

    Ensure the port-forward is running, restarting if needed.

  • get_config

    Return connection config with trusted headers.

  • health_check

    Check if the port-forward is healthy.

  • setup

    Start kubectl port-forward if not already running.

  • teardown

    Stop the port-forward process only if we started it.

Attributes:

Source code in src/unblu_mcp/_internal/providers_k8s.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def __init__(
    self,
    environment: str | K8sEnvironmentConfig = "dev",
    trusted_user_id: str = "superadmin",
    trusted_user_role: str = "SUPER_ADMIN",
    environments: dict[str, K8sEnvironmentConfig] | None = None,
) -> None:
    self._environments = environments or _get_default_environments()

    if isinstance(environment, str):
        if not self._environments:
            msg = (
                "No K8s environments are configured. Create ~/.unblu-mcp/k8s_environments.yaml, "
                "run from a source checkout with config/k8s_environments.yaml, or pass --k8s-config /path/to/k8s_environments.yaml."
            )
            raise ConfigurationError(msg)
        if environment not in self._environments:
            valid = ", ".join(self._environments.keys())
            msg = (
                f"Unknown environment '{environment}'. Valid environments: {valid}. "
                f"Update ~/.unblu-mcp/k8s_environments.yaml or pass --k8s-config with the right environment map."
            )
            raise ConfigurationError(msg)
        self._env_config = self._environments[environment]
    else:
        self._env_config = environment

    self._trusted_user_id = trusted_user_id
    self._trusted_user_role = trusted_user_role
    self._port_forward_process: subprocess.Popen[bytes] | None = None
    self._owns_port_forward = False  # Whether we started the port-forward

environment property

environment: str

Return the current environment name.

local_port property

local_port: int

Return the local port for this environment.

ensure_connection async

ensure_connection() -> None

Ensure the port-forward is running, restarting if needed.

Call this before making API requests to handle cases where: - Our port-forward process died - An external port-forward we were using is no longer available

Source code in src/unblu_mcp/_internal/providers_k8s.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
async def ensure_connection(self) -> None:
    """Ensure the port-forward is running, restarting if needed.

    Call this before making API requests to handle cases where:
    - Our port-forward process died
    - An external port-forward we were using is no longer available
    """
    if self._is_port_in_use():
        return  # Port is available, nothing to do

    # Port is not available - need to (re)start port-forward
    if self._owns_port_forward and self._port_forward_process is not None:
        # Clean up existing process (dead or malfunctioning)
        retcode = self._port_forward_process.poll()
        if retcode is not None:
            _logger.warning(
                "Port-forward process died (exit code %d), restarting...",
                retcode,
            )
        else:
            _logger.warning("Port-forward process alive but port not available, killing and restarting...")
            self._port_forward_process.kill()
            try:
                self._port_forward_process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                _logger.warning("Process did not terminate after kill, continuing anyway")
        self._port_forward_process = None

    # Start a new port-forward
    _logger.info("Restarting port-forward for %s", self._env_config.name)
    self._owns_port_forward = True
    await self._start_port_forward()

get_config

get_config() -> ConnectionConfig

Return connection config with trusted headers.

Source code in src/unblu_mcp/_internal/providers_k8s.py
325
326
327
328
329
330
331
332
333
def get_config(self) -> ConnectionConfig:
    """Return connection config with trusted headers."""
    return ConnectionConfig(
        base_url=f"http://localhost:{self._env_config.local_port}{self._env_config.api_path}",
        headers={
            "x-unblu-trusted-user-id": self._trusted_user_id,
            "x-unblu-trusted-user-role": self._trusted_user_role,
        },
    )

health_check async

health_check() -> bool

Check if the port-forward is healthy.

Source code in src/unblu_mcp/_internal/providers_k8s.py
335
336
337
async def health_check(self) -> bool:
    """Check if the port-forward is healthy."""
    return self._is_port_in_use()

setup async

setup() -> None

Start kubectl port-forward if not already running.

Uses a simple port-check approach: if the port is already in use, assume another instance is handling it. Otherwise, start our own.

Source code in src/unblu_mcp/_internal/providers_k8s.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
async def setup(self) -> None:
    """Start kubectl port-forward if not already running.

    Uses a simple port-check approach: if the port is already in use,
    assume another instance is handling it. Otherwise, start our own.
    """
    if self._is_port_in_use():
        # Port already in use - another instance or external process has it
        _logger.debug(
            "Port %d already in use, reusing existing connection",
            self._env_config.local_port,
        )
        self._owns_port_forward = False
    else:
        # Port not in use - we need to start port-forward
        _logger.debug("Port %d not in use, starting port-forward", self._env_config.local_port)
        self._owns_port_forward = True
        await self._start_port_forward()

teardown async

teardown() -> None

Stop the port-forward process only if we started it.

Source code in src/unblu_mcp/_internal/providers_k8s.py
279
280
281
282
283
284
285
286
287
288
289
290
async def teardown(self) -> None:
    """Stop the port-forward process only if we started it."""
    if self._owns_port_forward and self._port_forward_process is not None:
        _logger.debug("Stopping port-forward for %s", self._env_config.name)
        self._port_forward_process.terminate()
        try:
            self._port_forward_process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            self._port_forward_process.kill()
        self._port_forward_process = None
    elif not self._owns_port_forward:
        _logger.debug("Not owner, skipping port-forward cleanup for %s", self._env_config.name)

K8sEnvironmentConfig dataclass

K8sEnvironmentConfig(
    name: str,
    local_port: int,
    namespace: str,
    service: str = "haproxy",
    service_port: int = 8080,
    api_path: str = "/app/rest/v4",
)

Configuration for a Kubernetes environment.

Attributes:

api_path class-attribute instance-attribute

api_path: str = '/app/rest/v4'

API path prefix.

local_port instance-attribute

local_port: int

Local port for port-forwarding.

name instance-attribute

name: str

Environment name (e.g., dev, staging, prod).

namespace instance-attribute

namespace: str

Kubernetes namespace.

service class-attribute instance-attribute

service: str = 'haproxy'

Kubernetes service name.

service_port class-attribute instance-attribute

service_port: int = 8080

Service port to forward.

OperationInfo

Bases: BaseModel

Brief information about an API operation.

OperationMatch

Bases: BaseModel

A single matching API operation returned by find_operation.

OperationResult

Bases: _NextSteps

Result of a write operation (assign, end, etc.).

OperationSchema

Bases: BaseModel

Full schema for an API operation.

OperationSearchResult

Bases: _NextSteps

Result from find_operation.

PersonAmbiguousResult

Bases: _NextSteps

Returned when get_person finds multiple candidates.

PersonBatchEntry

Bases: BaseModel

One entry in a get_persons() batch result.

PersonBatchResult

Bases: _NextSteps

Result from get_persons() batch lookup.

PersonDetail

Bases: _NextSteps

Full person details for debugging.

PersonPage

Bases: _NextSteps

Paginated list of persons.

PersonSummary

Bases: BaseModel

Compact person info for list results.

ServiceInfo

Bases: BaseModel

Service/tag grouping of API operations.

UnbluAPIRegistry

UnbluAPIRegistry(spec: dict[str, Any])

Registry for Unblu API operations parsed from OpenAPI spec.

Methods:

Source code in src/unblu_mcp/_internal/server.py
136
137
138
139
140
141
142
def __init__(self, spec: dict[str, Any]) -> None:
    self.spec = spec
    self.services: dict[str, ServiceInfo] = {}
    self.operations: dict[str, dict[str, Any]] = {}
    self.operations_by_service: dict[str, list[str]] = {}
    self._schema_cache: dict[str, dict[str, Any]] = {}
    self._parse_spec()

get_operation_schema

get_operation_schema(
    operation_id: str,
) -> OperationSchema | None

Get full schema for an operation.

Source code in src/unblu_mcp/_internal/server.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def get_operation_schema(self, operation_id: str) -> OperationSchema | None:
    """Get full schema for an operation."""
    op = self.operations.get(operation_id)
    if not op:
        return None
    if operation_id in self._schema_cache:
        return OperationSchema(**self._schema_cache[operation_id])
    parameters = self._resolve_refs(op["parameters"])
    request_body = self._resolve_refs(op["request_body"]) if op["request_body"] else None
    schema = OperationSchema(
        operation_id=op["operation_id"],
        method=op["method"],
        path=op["path"],
        summary=op["summary"],
        description=op.get("description"),
        parameters=parameters,
        request_body=request_body,
        responses=op["responses"],
    )
    self._schema_cache[operation_id] = schema.model_dump()
    return schema

list_operations

list_operations(service: str) -> list[OperationInfo]

List all operations for a service (returns empty list for unknown service).

Source code in src/unblu_mcp/_internal/server.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def list_operations(self, service: str) -> list[OperationInfo]:
    """List all operations for a service (returns empty list for unknown service)."""
    key = self._find_service_key(service)
    if not key:
        return []
    return [
        OperationInfo(
            operation_id=op_id,
            method=self.operations[op_id]["method"],
            path=self.operations[op_id]["path"],
            summary=self.operations[op_id]["summary"],
            service=key,
        )
        for op_id in self.operations_by_service.get(key, [])
        if op_id in self.operations
    ]

list_services

list_services() -> list[ServiceInfo]

List all available API services.

Source code in src/unblu_mcp/_internal/server.py
191
192
193
def list_services(self) -> list[ServiceInfo]:
    """List all available API services."""
    return sorted(self.services.values(), key=lambda s: s.name)

search_operations

search_operations(
    query: str,
    service: str | None = None,
    include_infra: bool = False,
    limit: int = 10,
) -> list[OperationInfo]

Search operations by keyword with optional service + infra filtering.

Source code in src/unblu_mcp/_internal/server.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def search_operations(
    self,
    query: str,
    service: str | None = None,
    include_infra: bool = False,
    limit: int = 10,
) -> list[OperationInfo]:
    """Search operations by keyword with optional service + infra filtering."""
    query_lower = query.lower()
    results: list[tuple[int, dict[str, Any]]] = []
    for op_id, op in self.operations.items():
        svc = op.get("service", "")
        if service and svc.lower() != service.lower():
            continue
        if not include_infra and svc in _INFRA_SERVICES:
            continue
        score = 0
        if query_lower in op_id.lower():
            score += 3
        if query_lower in op["path"].lower():
            score += 2
        if query_lower in op["summary"].lower():
            score += 1
        if query_lower in (op.get("description") or "").lower():
            score += 1
        if score > 0:
            results.append((score, op))

    results.sort(key=lambda x: -x[0])
    return [
        OperationInfo(
            operation_id=op["operation_id"],
            method=op["method"],
            path=op["path"],
            summary=op["summary"],
            service=op.get("service", ""),
        )
        for _, op in results[:limit]
    ]

UserDetail

Bases: _NextSteps

Full user details.

UserPage

Bases: _NextSteps

Paginated list of users.

UserSummary

Bases: BaseModel

Compact user info for list results.

build_query_body

build_query_body(
    offset: int = 0,
    limit: int = 25,
    search_filters: list[dict[str, Any]] | None = None,
    order_by: list[dict[str, Any]] | None = None,
    query_type: str = "Query",
) -> dict[str, Any]

Build an Unblu search/query request body with pagination.

Parameters:

  • offset (int, default: 0 ) –

    Zero-based item offset for the current page.

  • limit (int, default: 25 ) –

    Maximum number of items to return.

  • search_filters (list[dict[str, Any]] | None, default: None ) –

    List of filter dicts (Unblu SearchFilter schema).

  • order_by (list[dict[str, Any]] | None, default: None ) –

    List of order-by dicts (Unblu OrderBy schema).

  • query_type (str, default: 'Query' ) –

    The $_type discriminator for the query body.

Returns:

  • dict[str, Any]

    Dict ready to pass as the JSON body to a search endpoint.

Source code in src/unblu_mcp/_internal/pagination.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def build_query_body(
    offset: int = 0,
    limit: int = 25,
    search_filters: list[dict[str, Any]] | None = None,
    order_by: list[dict[str, Any]] | None = None,
    query_type: str = "Query",
) -> dict[str, Any]:
    """Build an Unblu search/query request body with pagination.

    Args:
        offset: Zero-based item offset for the current page.
        limit: Maximum number of items to return.
        search_filters: List of filter dicts (Unblu SearchFilter schema).
        order_by: List of order-by dicts (Unblu OrderBy schema).
        query_type: The $_type discriminator for the query body.

    Returns:
        Dict ready to pass as the JSON body to a search endpoint.
    """
    body: dict[str, Any] = {
        "$_type": query_type,
        "offset": offset,
        "limit": limit,
    }
    if search_filters:
        body["searchFilters"] = search_filters
    if order_by:
        body["orderBy"] = order_by
    return body

create_server

create_server(
    spec_path: str | Path | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    username: str | None = None,
    password: str | None = None,
    provider: ConnectionProvider | None = None,
) -> FastMCP

Create the Unblu MCP server.

Parameters:

  • spec_path (str | Path | None, default: None ) –

    Path to swagger.json. Defaults to package-bundled swagger.json.

  • base_url (str | None, default: None ) –

    Unblu API base URL. Defaults to UNBLU_BASE_URL env var.

  • api_key (str | None, default: None ) –

    API key for authentication. Defaults to UNBLU_API_KEY env var.

  • username (str | None, default: None ) –

    Username for basic auth. Defaults to UNBLU_USERNAME env var.

  • password (str | None, default: None ) –

    Password for basic auth. Defaults to UNBLU_PASSWORD env var.

  • provider (ConnectionProvider | None, default: None ) –

    Optional connection provider (e.g. K8s port-forward).

Source code in src/unblu_mcp/_internal/server.py
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
def create_server(  # noqa: PLR0913, PLR0917, PLR0915
    spec_path: str | Path | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    username: str | None = None,
    password: str | None = None,
    provider: ConnectionProvider | None = None,
) -> FastMCP:
    """Create the Unblu MCP server.

    Args:
        spec_path: Path to swagger.json. Defaults to package-bundled swagger.json.
        base_url: Unblu API base URL. Defaults to UNBLU_BASE_URL env var.
        api_key: API key for authentication. Defaults to UNBLU_API_KEY env var.
        username: Username for basic auth. Defaults to UNBLU_USERNAME env var.
        password: Password for basic auth. Defaults to UNBLU_PASSWORD env var.
        provider: Optional connection provider (e.g. K8s port-forward).
    """
    from unblu_mcp._internal.providers import DefaultConnectionProvider  # noqa: PLC0415

    if provider is None:
        provider = DefaultConnectionProvider(
            base_url=base_url,
            api_key=api_key,
            username=username,
            password=password,
        )

    @asynccontextmanager
    async def lifespan(_mcp: FastMCP) -> AsyncIterator[None]:
        await provider.setup()
        try:
            yield
        finally:
            await provider.teardown()

    config = provider.get_config()

    # Load OpenAPI spec
    if spec_path is None:
        try:
            spec_file = importlib.resources.files("unblu_mcp").joinpath("swagger.json")
            spec_content = spec_file.read_text(encoding="utf-8")
            spec = json.loads(spec_content)
        except FileNotFoundError, TypeError:
            candidates = [Path.cwd() / "swagger.json"]
            for candidate in candidates:
                if candidate.exists():
                    with Path(candidate).open(encoding="utf-8") as f:
                        spec = json.load(f)
                    break
            else:
                msg = "swagger.json not found. Please provide spec_path."
                raise FileNotFoundError(msg)
    else:
        with Path(spec_path).open(encoding="utf-8") as f:
            spec = json.load(f)

    registry = UnbluAPIRegistry(spec)

    client = httpx.AsyncClient(
        base_url=config.base_url,
        headers=config.headers,
        auth=config.auth,
        timeout=config.timeout,
    )

    mcp = FastMCP(
        name="unblu-mcp",
        lifespan=lifespan,
        mask_error_details=True,
        instructions="""Unblu MCP Server — Deployment Operations & Debugging

Primary use: verify deployment health, find conversations, inspect participants, audit activity.

## Core tools (always visible)
- get_current_account()         — confirm connectivity and identify the account (always call first)
- search_conversations(status=) — list/filter conversations by state, assignee, or topic
- search_persons(person_type=)  — find agents, visitors, bots by type or free-text

## Discovery — use search_tools(query=...) to find any tool by description
Then use call_tool(name=..., arguments={...}) to invoke it.
Key tools discoverable via search:
- find_operation / execute_operation — search and run any of 300+ API operations
- get_conversation, assign_conversation, end_conversation
- get_person, get_persons, search_users, get_user
- check_agent_availability, search_named_areas
- check_deployment_health() — 7-check health report: license, bots, webhooks, interceptors, availability

## Resources (read without a tool call)
- api://services                  — full service catalog
- api://operations/{operation_id} — full schema for any operation
""",
    )

    # ------------------------------------------------------------------
    # Middleware
    # ------------------------------------------------------------------
    mcp.add_middleware(
        ResponseCachingMiddleware(
            call_tool_settings=CallToolSettings(
                included_tools=["find_operation"],
            ),
        )
    )
    mcp.add_middleware(ErrorHandlingMiddleware())
    mcp.add_middleware(
        LoggingMiddleware(
            include_payloads=True,
            max_payload_length=1000,
        )
    )

    mcp.add_transform(
        BM25SearchTransform(
            max_results=8,
            always_visible=[
                "get_current_account",
                "search_conversations",
                "search_persons",
            ],
        )
    )

    # ------------------------------------------------------------------
    # Resources
    # ------------------------------------------------------------------

    @mcp.resource(
        "api://services",
        name="Unblu API Service Catalog",
        description=("Full catalog of all Unblu API services with name, description, operation count, and tier (curated/long-tail/infra)."),
        mime_type="application/json",
    )
    def services_catalog() -> str:
        return json.dumps([s.model_dump() for s in registry.list_services()], indent=2)

    @mcp.resource(
        "api://operations/{operation_id}",
        name="Unblu API Operation Schema",
        description=("Full resolved schema for any Unblu API operation: method, path, parameters, request body, and response shapes."),
        mime_type="application/json",
    )
    def operation_schema_resource(operation_id: str) -> str:
        schema = registry.get_operation_schema(operation_id)
        if not schema:
            return json.dumps({"error": f"Operation '{operation_id}' not found."})
        return json.dumps(schema.model_dump(), indent=2)

    # ------------------------------------------------------------------
    # Tool helpers
    # ------------------------------------------------------------------

    async def _ctx_log(ctx: Context, message: str) -> None:
        """Log to context; silently no-ops when no MCP session is established."""
        with contextlib.suppress(RuntimeError):
            await ctx.info(message)

    def _error_hint(status_code: int) -> str:
        """Return an error classification hint for agents."""
        if status_code == _HTTP_RATE_LIMIT:
            return " [RATE_LIMITED] Wait a few seconds and retry the same call."
        if status_code >= _HTTP_SERVER_ERROR:
            return " [SERVER_ERROR] May be transient — retry once. If it persists, the Unblu backend may be down."
        return " [PERMANENT] Do not retry without changing parameters."

    def _gui_url(resource: str, resource_id: str) -> str | None:
        """Build an Unblu admin console URL for a resource, or None if base URL is unknown."""
        raw = os.getenv("UNBLU_BASE_URL", "")
        if not raw or not resource_id:
            return None
        parsed = urllib.parse.urlparse(raw)
        origin = f"{parsed.scheme}://{parsed.netloc}"
        return f"{origin}/unblu/index.html#/{resource}/{resource_id}"

    async def _request(
        method: str,
        path: str,
        query_params: dict[str, Any] | None = None,
        body: dict[str, Any] | None = None,
    ) -> tuple[int, Any]:
        """Send an HTTP request and return (status_code, parsed_body)."""
        await provider.ensure_connection()
        try:
            response = await client.request(
                method=method,
                url=path,
                params=query_params,
                json=body or None,
            )
        except httpx.RequestError as e:
            msg = f"API request failed: {e!s} [NETWORK_ERROR] This is likely transient — retry."
            raise ToolError(msg) from e

        if response.status_code == _HTTP_NO_CONTENT:
            return _HTTP_NO_CONTENT, {}

        try:
            data = response.json()
        except Exception:
            data = {"raw": response.text[:500]}

        return response.status_code, data

    def _truncate(data: Any, max_chars: int = _DEFAULT_TRUNCATE_CHARS) -> tuple[Any, bool]:
        """Truncate a response to max_chars of JSON. Returns (data, was_truncated)."""
        serialised = json.dumps(data, separators=(",", ":"))
        if len(serialised) <= max_chars:
            return data, False
        if isinstance(data, dict):
            return {"_truncated": True, "_keys": list(data.keys())[:20]}, True
        if isinstance(data, list):
            return {"_truncated": True, "_count": len(data), "_first_3": data[:3]}, True
        return {"_truncated": True}, True

    def _filter_fields(data: Any, fields: list[str]) -> Any:
        """Filter response data to include only specified dot-notation field paths."""
        if not fields or not isinstance(data, dict):
            return data
        result: dict[str, Any] = {}
        for field_path in fields:
            parts = field_path.split(".")
            current = data
            current_result = result
            for i, part in enumerate(parts):
                if isinstance(current, dict) and part in current:
                    if i == len(parts) - 1:
                        current_result[part] = current[part]
                    else:
                        if part not in current_result:
                            current_result[part] = {}
                        current_result = current_result[part]
                        current = current[part]
                else:
                    break
        return result

    # ------------------------------------------------------------------
    # Tool 1 — find_operation
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Find API Operation",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def find_operation(  # noqa: PLR0913, PLR0917
        ctx: Context,
        query: str,
        service: str | None = None,
        include_schema: bool = True,
        include_infra: bool = False,
        limit: int = 10,
    ) -> OperationSearchResult:
        """Search Unblu API operations by keyword and return their schemas.

        Replaces list_services(), list_operations(), search_operations(), and
        get_operation_schema() — one call is enough for debugging.

        Args:
            query: Keyword to search — matches operation IDs, paths, summaries,
                   and descriptions. Examples: "conversation", "search agents",
                   "create user", "bot message", "audit".
            service: Optional service name to restrict the search (e.g. "Conversations",
                     "Persons", "Users"). Read api://services for the full list.
            include_schema: When True (default), embeds the full resolved schema
                            (parameters, request body) in each match so you can
                            call execute_operation() without a separate lookup.
            include_infra: When True, includes infrastructure/security-sensitive
                           services (WebhookRegistrations, ApiKeys, Authenticator,
                           etc.) that are hidden by default.
            limit: Maximum number of results to return (default 10).

        Returns:
            Ranked matching operations with schema_resource URIs. Call
            execute_operation(operation_id=...) to run any of them.
        """
        await _ctx_log(ctx, f"Searching {len(registry.operations)} operations for '{query}'")
        matches_info = registry.search_operations(
            query=query,
            service=service,
            include_infra=include_infra,
            limit=limit,
        )

        matches: list[OperationMatch] = []
        for info in matches_info:
            schema_data: dict[str, Any] | None = None
            if include_schema:
                full = registry.get_operation_schema(info.operation_id)
                if full:
                    schema_data = full.model_dump()
            matches.append(
                OperationMatch(
                    operation_id=info.operation_id,
                    method=info.method,
                    path=info.path,
                    summary=info.summary,
                    service=info.service,
                    schema_resource=f"api://operations/{info.operation_id}",
                    full_schema=schema_data,
                )
            )

        next_steps = [
            "Call execute_operation(operation_id='<id>') to run any matched operation.",
            "Read api://services to browse all available service categories.",
        ]
        if not matches:
            next_steps.insert(0, f"No results for '{query}'. Try a broader term or set include_infra=True.")
        return OperationSearchResult(
            matches=matches,
            total_searched=len(registry.operations),
            next_steps=next_steps,
        )

    # ------------------------------------------------------------------
    # Tool 2 — execute_operation  (improved call_api escape hatch)
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Execute API Operation",
            "readOnlyHint": False,
            "destructiveHint": True,
            "idempotentHint": False,
            "openWorldHint": True,
        },
    )
    async def execute_operation(  # noqa: PLR0913, PLR0917, PLR0912
        ctx: Context,
        operation_id: str,
        path_params: dict[str, str] | None = None,
        query_params: dict[str, Any] | None = None,
        body: dict[str, Any] | None = None,
        fields: list[str] | None = None,
        offset: int | None = None,
        limit: int | None = None,
        confirm_destructive: bool = False,
        max_response_size: int | None = None,
    ) -> ExecuteResult:
        """Execute any Unblu API operation by its operation_id.

        Use find_operation(query) first to discover operation_ids and their
        required parameters. This is the escape hatch for the 300+ operations
        that do not have dedicated curated tools.

        Args:
            operation_id: The operation to run (e.g. "conversationsRead").
                          Use find_operation() to discover valid operation IDs.
            path_params: Path parameters as a dict (e.g. {"conversationId": "abc"}).
                         Required when the path contains placeholders.
            query_params: Query string parameters as a dict.
            body: JSON request body for POST/PUT/PATCH operations.
            fields: Optional list of dot-notation field paths to include in the
                    response (e.g. ["id", "topic", "participants.personId"]).
                    Use to reduce response size for large payloads.
            offset: Page offset for paginated operations. Auto-merged into body
                    for POST search endpoints.
            limit: Page size for paginated operations. Auto-merged into body
                   for POST search endpoints.
            confirm_destructive: Must be True for destructive operations (DELETE).
                                 This is a safety gate — the error message will tell you
                                 exactly what will be deleted before you confirm.
            max_response_size: Optional maximum size of the response in characters.
                               If the response exceeds this size, it will be truncated.

        Returns:
            status_code, data (shaped by fields if provided), has_more, next_offset,
            and next_steps hints.
        """
        op = registry.operations.get(operation_id)
        if not op:
            msg = f"Operation '{operation_id}' not found. Call find_operation(query='...') to search for valid operation IDs."
            raise ToolError(msg)

        await _ctx_log(ctx, f"Executing {op['method']} {op['path']}")

        # Build URL with path parameters (validate before destructive check)
        path = op["path"]
        if path_params:
            for key, value in path_params.items():
                path = path.replace(f"{{{key}}}", str(value))

        if "{" in path:
            missing = re.findall(r"\{(\w+)\}", path)[:3]
            msg = (
                f"Missing required path parameters: {missing}. "
                f"Call find_operation(query='{operation_id}', include_schema=True) "
                "to see all required parameters."
            )
            raise ToolError(msg)

        # Safety gate for destructive operations
        if op["method"] == "DELETE" and not confirm_destructive:
            msg = (
                f"Operation '{operation_id}' is a DELETE ({op['path']}). "
                "This will permanently remove data. "
                "Call again with confirm_destructive=True to proceed."
            )
            raise ToolError(msg)

        # Merge offset/limit into body for POST search-style operations
        method = op["method"]
        request_body = dict(body or {})
        if (offset is not None or limit is not None) and method in {"POST", "PUT", "PATCH"}:
            if offset is not None:
                request_body["offset"] = offset
            if limit is not None:
                request_body["limit"] = limit
        effective_body = request_body or None

        # For GET operations, merge offset/limit into query params
        effective_query = dict(query_params or {})
        if (offset is not None or limit is not None) and method == "GET":
            if offset is not None:
                effective_query["offset"] = offset
            if limit is not None:
                effective_query["limit"] = limit

        status_code, data = await _request(
            method=method,
            path=path,
            query_params=effective_query or None,
            body=effective_body,
        )

        # Parse pagination from response (must happen before field filtering to preserve
        # pagination keys like hasMoreItems/nextOffset)
        has_more: bool | None = None
        next_offset_val: int | None = None
        if isinstance(data, dict) and "hasMoreItems" in data:
            has_more, next_offset_val = parse_pagination(data)
            # Unwrap items, applying field filtering per item if requested
            items_data: list[Any] = data.get("items", [])
            if fields:
                items_data = [_filter_fields(item, fields) for item in items_data]
            data = {"items": items_data, "total_in_page": len(items_data)}
        elif fields and isinstance(data, dict):
            # Non-paginated: filter the whole response dict
            data = _filter_fields(data, fields)

        # Truncate large responses
        data, truncated = _truncate(
            data,
            max_chars=max_response_size if max_response_size is not None else _DEFAULT_TRUNCATE_CHARS,
        )

        next_steps: list[str] = []
        if has_more and next_offset_val is not None:
            next_steps.append(f"Call execute_operation('{operation_id}', offset={next_offset_val}) for the next page.")
        if status_code >= _HTTP_CLIENT_ERROR:
            next_steps.append(
                f"Request failed (HTTP {status_code}). "
                f"Call find_operation('{operation_id}', include_schema=True) to verify required parameters."
            )

        return ExecuteResult(
            status_code=status_code,
            data=data,
            has_more=has_more,
            next_offset=next_offset_val,
            truncated=truncated,
            next_steps=next_steps,
        )

    # ------------------------------------------------------------------
    # Tool 3 — get_current_account
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Get Current Account",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def get_current_account(
        ctx: Context,
    ) -> AccountInfo:
        """Get information about the Unblu account you are connected to.

        Always a good first call to confirm connectivity and identify the account.

        Returns:
            Account id, name, and next_steps pointing to other useful tools.
        """
        await _ctx_log(ctx, "Fetching current account info")
        status_code, data = await _request("GET", "/accounts/getCurrentAccount")
        if status_code >= _HTTP_CLIENT_ERROR:
            hint = _error_hint(status_code)
            msg = (
                f"Failed to get current account (HTTP {status_code}). "
                f"Verify UNBLU_BASE_URL, UNBLU_API_KEY, or UNBLU_USERNAME/PASSWORD.{hint}"
            )
            raise ToolError(msg)
        result = AccountInfo(
            id=data.get("id", ""),
            name=data.get("name") or data.get("displayName"),
        )
        with contextlib.suppress(RuntimeError):
            await ctx.set_state("account_id", result.id)
            await ctx.set_state("account_name", result.name or "")
        return result

    # ------------------------------------------------------------------
    # Tool 4 — search_conversations
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Search Conversations",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def search_conversations(  # noqa: PLR0913, PLR0917
        ctx: Context,
        status: Literal["CREATED", "ONBOARDING", "REBOARDING", "QUEUED", "ACTIVE", "UNASSIGNED", "OFFBOARDING", "ENDED"] | None = None,
        assignee_person_id: str | None = None,
        topic: str | None = None,
        offset: int = 0,
        limit: int = 25,
        fields: list[str] | None = None,
    ) -> ConversationPage:
        """Search and list Unblu conversations with optional filters.

        Args:
            status: Filter by conversation state. Common values: ACTIVE (agent is
                    engaged), QUEUED (waiting for agent), ENDED (completed).
                    ONBOARDING/OFFBOARDING are transition states.
            assignee_person_id: Filter by assigned agent person ID (UUID).
                                 Use search_persons(person_type="AGENT") to find IDs.
            topic: Filter by topic text (case-insensitive contains match).
            offset: Page offset for pagination (default 0).
            limit: Number of conversations to return (default 25, max ~100).
            fields: Optional list of field names to include in each item (e.g.
                    ["id", "state"]). When set, items are returned as filtered dicts
                    instead of full objects, reducing token usage on large result sets.

        Returns:
            Paginated list of conversations with id, topic, status, timestamps,
            participant count, and pagination info.
        """
        await _ctx_log(ctx, f"Searching conversations (status={status}, offset={offset})")

        search_filters: list[dict[str, Any]] = []

        if status:
            search_filters.append({
                "$_type": "ConversationStateSearchFilter",
                "field": "STATE",
                "operator": {
                    "$_type": "EConversationStateOperator",
                    "type": "EQUALS",
                    "value": status,
                },
            })

        if assignee_person_id:
            search_filters.append({
                "$_type": "AssigneePersonIdConversationSearchFilter",
                "field": "ASSIGNEE_PERSON_ID",
                "operator": {
                    "$_type": "IdOperator",
                    "type": "EQUALS",
                    "value": assignee_person_id,
                },
            })

        if topic:
            search_filters.append({
                "$_type": "TopicConversationSearchFilter",
                "field": "TOPIC",
                "operator": {
                    "$_type": "StringOperator",
                    "type": "CONTAINS",
                    "value": topic,
                },
            })

        body = build_query_body(
            offset=offset,
            limit=limit,
            search_filters=search_filters or None,
            query_type="ConversationQuery",
        )

        status_code, data = await _request("POST", "/conversations/search", body=body)
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = f"Conversation search failed (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
            raise ToolError(msg)

        has_more, next_offset_val = parse_pagination(data)
        raw_items: list[dict[str, Any]] = data.get("items", [])

        if fields:
            items: list[Any] = [_filter_fields(c, fields) for c in raw_items]
        else:
            items = [
                ConversationSummary(
                    id=c.get("id", ""),
                    topic=c.get("topic"),
                    state=c.get("state", ""),
                    created_at=c.get("creationTimestamp"),
                    ended_at=c.get("endTimestamp"),
                    awaited_person_type=c.get("awaitedPersonType"),
                    participant_count=len(c.get("participants", [])),
                    bot_participant_count=len(c.get("botParticipants", [])),
                    source_url=c.get("sourceUrl"),
                )
                for c in raw_items
            ]

        next_steps = ["Call get_conversation(conversation_id='<id>') for full details."]
        if has_more:
            next_steps.append(f"Call search_conversations(offset={next_offset_val}) to get the next page.")

        return ConversationPage(
            items=items,
            has_more=has_more,
            next_offset=next_offset_val,
            next_steps=next_steps,
        )

    # ------------------------------------------------------------------
    # Tool 5 — get_conversation
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Get Conversation",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def get_conversation(
        ctx: Context,
        conversation_id: str,
    ) -> ConversationDetail:
        """Get full details of a specific conversation for debugging.

        Args:
            conversation_id: UUID of the conversation. Use search_conversations()
                             to find valid IDs.

        Returns:
            Full conversation details: state, timestamps, participants list
            (person IDs and types), source URL, metadata, and suggested next steps.
            Note: raw configuration and text blobs are excluded to reduce noise.
        """
        await _ctx_log(ctx, f"Fetching conversation {conversation_id}")
        status_code, data = await _request("GET", f"/conversations/{conversation_id}")
        if status_code == _HTTP_NOT_FOUND:
            msg = f"Conversation '{conversation_id}' not found. Call search_conversations() to find valid IDs. [PERMANENT]"
            raise ToolError(msg)
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = f"Failed to get conversation (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
            raise ToolError(msg)

        participants = [
            ConversationParticipant(
                person_id=p.get("personId", ""),
                participation_type=p.get("participationType"),
                state=p.get("state"),
                hidden=p.get("hidden", False),
            )
            for p in data.get("participants", [])
        ]

        return ConversationDetail(
            id=data.get("id", ""),
            topic=data.get("topic"),
            state=data.get("state", ""),
            created_at=data.get("creationTimestamp"),
            ended_at=data.get("endTimestamp"),
            visibility=data.get("conversationVisibility"),
            locale=data.get("locale"),
            awaited_person_type=data.get("awaitedPersonType"),
            source_url=data.get("sourceUrl"),
            source_id=data.get("sourceId"),
            initial_engagement_type=data.get("initialEngagementType"),
            end_reason=data.get("endReason"),
            participants=participants,
            bot_participant_count=len(data.get("botParticipants", [])),
            metadata=data.get("metadata"),
            gui_url=_gui_url("conversations", data.get("id", "")),
            next_steps=[
                "Call get_person(identifier='<personId>') to inspect any participant.",
                "Call assign_conversation(conversation_id, assignee_person_id) to reassign.",
                "Call end_conversation(conversation_id) to close this conversation.",
                "Call search_conversations() to list other conversations.",
            ],
        )

    # ------------------------------------------------------------------
    # Tool 6 — assign_conversation
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Assign Conversation",
            "readOnlyHint": False,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": False,
        },
    )
    async def assign_conversation(
        ctx: Context,
        conversation_id: str,
        assignee_person_id: str,
    ) -> OperationResult:
        """Assign a conversation to a specific agent person.

        Useful during debugging to test assignment logic or reassign
        conversations for investigation purposes.

        Args:
            conversation_id: UUID of the conversation to reassign.
            assignee_person_id: UUID of the agent person to assign to.
                                Use search_persons(person_type="AGENT") to find valid IDs.

        Returns:
            Success status and confirmation message.
        """
        await _ctx_log(ctx, f"Assigning conversation {conversation_id} to {assignee_person_id}")
        status_code, data = await _request(
            "POST",
            f"/conversations/{conversation_id}/setAssigneePerson",
            body={"personId": assignee_person_id},
        )
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = (
                f"Failed to assign conversation (HTTP {status_code}): {str(data)[:200]}. "
                "Verify conversation_id with get_conversation() and "
                f"assignee_person_id with search_persons(person_type='AGENT').{_error_hint(status_code)}"
            )
            raise ToolError(msg)
        return OperationResult(
            success=True,
            message=f"Conversation {conversation_id} assigned to {assignee_person_id}.",
            conversation_id=conversation_id,
            next_steps=[
                f"Call get_conversation('{conversation_id}') to verify the new assignment.",
            ],
        )

    # ------------------------------------------------------------------
    # Tool 7 — end_conversation
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "End Conversation",
            "readOnlyHint": False,
            "destructiveHint": True,
            "idempotentHint": False,
            "openWorldHint": False,
        },
    )
    async def end_conversation(
        ctx: Context,
        conversation_id: str,
    ) -> OperationResult:
        """End (close) a conversation. This action is irreversible.

        Useful during debugging to clean up test conversations.
        The conversation transitions to ENDED state.

        Args:
            conversation_id: UUID of the conversation to end.
                             Use search_conversations() to find valid IDs.

        Returns:
            Success status and confirmation message.
        """
        await _ctx_log(ctx, f"Ending conversation {conversation_id}")
        status_code, data = await _request(
            "POST",
            f"/conversations/{conversation_id}/end",
            body={"$_type": "ConversationsEndBody"},
        )
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = (
                f"Failed to end conversation (HTTP {status_code}): {str(data)[:200]}. "
                "Verify the conversation exists and is not already ended "
                f"with get_conversation('{conversation_id}').{_error_hint(status_code)}"
            )
            raise ToolError(msg)
        return OperationResult(
            success=True,
            message=f"Conversation {conversation_id} has been ended.",
            conversation_id=conversation_id,
            next_steps=[
                f"Call get_conversation('{conversation_id}') to verify the ENDED state.",
            ],
        )

    # ------------------------------------------------------------------
    # Tool 8 — search_persons
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Search Persons",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def search_persons(  # noqa: PLR0913, PLR0917
        ctx: Context,
        query: str | None = None,
        person_type: Literal["AGENT", "VISITOR", "BOT", "SYSTEM"] | None = None,
        offset: int = 0,
        limit: int = 25,
        fields: list[str] | None = None,
    ) -> PersonPage:
        """Search Unblu persons (real-time session participants).

        Persons are the live participants in conversations: agents handling chats,
        visitors initiating conversations, bots, and system users.
        For admin-level Unblu user accounts, use search_users() instead.

        Args:
            query: Free-text search across display name, email, username, first/last name.
            person_type: Filter by type. AGENT = human support agents,
                         VISITOR = end-users/customers, BOT = automated bots,
                         SYSTEM = internal system persons.
            offset: Page offset for pagination (default 0).
            limit: Number of persons to return (default 25).
            fields: Optional list of field names to include per item (e.g. ["id",
                    "personType"]). When set, items are filtered dicts instead of
                    full PersonSummary objects, reducing token usage.

        Returns:
            Paginated list of persons with id, display_name, type, email, team.
        """
        await _ctx_log(ctx, f"Searching persons (type={person_type}, query={query}, offset={offset})")

        # Choose the most specific endpoint based on person_type
        if person_type == "AGENT":
            endpoint = "/persons/searchAgents"
            query_type = "PersonTypedQuery"
        elif person_type == "BOT":
            endpoint = "/persons/searchBots"
            query_type = "PersonTypedQuery"
        elif person_type == "VISITOR":
            endpoint = "/persons/searchVisitors"
            query_type = "PersonTypedQuery"
        else:
            endpoint = "/persons/search"
            query_type = "PersonQuery"

        search_filters: list[dict[str, Any]] = []

        if query:
            search_filters.append({
                "$_type": "CompoundPersonSearchFilter",
                "field": "COMPOUND",
                "operator": {
                    "$_type": "StringOperator",
                    "type": "CONTAINS",
                    "value": query,
                },
            })

        # Add type filter only when using the generic /persons/search endpoint
        if person_type and endpoint == "/persons/search":
            search_filters.append({
                "$_type": "PersonTypePersonSearchFilter",
                "field": "PERSON_TYPE",
                "operator": {
                    "$_type": "EPersonTypeOperator",
                    "type": "EQUALS",
                    "value": person_type,
                },
            })

        body = build_query_body(
            offset=offset,
            limit=limit,
            search_filters=search_filters or None,
            query_type=query_type,
        )

        status_code, data = await _request("POST", endpoint, body=body)
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = f"Person search failed (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
            raise ToolError(msg)

        has_more, next_offset_val = parse_pagination(data)
        raw_items: list[dict[str, Any]] = data.get("items", [])

        if fields:
            items: list[Any] = [_filter_fields(p, fields) for p in raw_items]
        else:
            items = [
                PersonSummary(
                    id=p.get("id", ""),
                    display_name=p.get("displayName"),
                    person_type=p.get("personType"),
                    email=p.get("email"),
                    team_id=p.get("teamId"),
                    authorization_role=p.get("authorizationRole"),
                )
                for p in raw_items
            ]

        next_steps = ["Call get_person(identifier='<id>') for full person details."]
        if has_more:
            next_steps.append(f"Call search_persons(offset={next_offset_val}) to get the next page.")

        return PersonPage(
            items=items,
            has_more=has_more,
            next_offset=next_offset_val,
            next_steps=next_steps,
        )

    # ------------------------------------------------------------------
    # Tool 9 — get_person
    # ------------------------------------------------------------------

    async def _resolve_person(ctx: Context, identifier: str) -> PersonDetail | PersonAmbiguousResult:
        """Resolve a person by UUID, email, or name. Used by get_person and get_persons."""
        await _ctx_log(ctx, f"Looking up person: {identifier}")

        # Strategy 1: UUID direct lookup (fastest — single GET)
        if _UUID_RE.match(identifier):
            status_code, data = await _request("GET", f"/persons/{identifier}")
            if status_code == _HTTP_NOT_FOUND:
                msg = f"Person '{identifier}' not found. Call search_persons() to browse available persons. [PERMANENT]"
                raise ToolError(msg)
            if status_code >= _HTTP_CLIENT_ERROR:
                msg = f"Failed to fetch person (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
                raise ToolError(msg)
            return _person_detail(data)

        # Strategy 2: Email search (exact match)
        if "@" in identifier:
            body = build_query_body(
                offset=0,
                limit=5,
                search_filters=[
                    {
                        "$_type": "EmailPersonSearchFilter",
                        "field": "EMAIL",
                        "operator": {
                            "$_type": "StringOperator",
                            "type": "EQUALS",
                            "value": identifier,
                        },
                    }
                ],
                query_type="PersonQuery",
            )
            status_code, data = await _request("POST", "/persons/search", body=body)
            items: list[dict[str, Any]] = data.get("items", []) if status_code < _HTTP_CLIENT_ERROR else []
            if len(items) == 1:
                return _person_detail(items[0])
            if len(items) > 1:
                return PersonAmbiguousResult(
                    candidates=[
                        PersonSummary(
                            id=p.get("id", ""),
                            display_name=p.get("displayName"),
                            person_type=p.get("personType"),
                            email=p.get("email"),
                            team_id=p.get("teamId"),
                        )
                        for p in items
                    ],
                    next_steps=["Call get_person(identifier='<person_id>') with the exact UUID."],
                )
            msg = f"No person found with email '{identifier}'. Call search_persons() to browse available persons. [PERMANENT]"
            raise ToolError(msg)

        # Strategy 3: Compound text search (slower — POST search)
        body = build_query_body(
            offset=0,
            limit=10,
            search_filters=[
                {
                    "$_type": "CompoundPersonSearchFilter",
                    "field": "COMPOUND",
                    "operator": {
                        "$_type": "StringOperator",
                        "type": "CONTAINS",
                        "value": identifier,
                    },
                }
            ],
            query_type="PersonQuery",
        )
        status_code, data = await _request("POST", "/persons/search", body=body)
        items = data.get("items", []) if status_code < _HTTP_CLIENT_ERROR else []

        if len(items) == 1:
            return _person_detail(items[0])
        if len(items) > 1:
            return PersonAmbiguousResult(
                candidates=[
                    PersonSummary(
                        id=p.get("id", ""),
                        display_name=p.get("displayName"),
                        person_type=p.get("personType"),
                        email=p.get("email"),
                        team_id=p.get("teamId"),
                    )
                    for p in items
                ],
                next_steps=["Call get_person(identifier='<person_id>') with the exact UUID."],
            )
        msg = f"No person found matching '{identifier}'. Try search_persons(query='...') for a broader search. [PERMANENT]"
        raise ToolError(msg)

    @mcp.tool(
        annotations={
            "title": "Get Person",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def get_person(
        ctx: Context,
        identifier: str,
    ) -> PersonDetail | PersonAmbiguousResult:
        """Get full details of a person by UUID, email, or display name.

        Accepts natural identifiers — you do not need to know the internal UUID.
        Resolution strategy (fastest to slowest):
        - UUID (e.g. "a1b2c3d4-..."): direct GET — fastest, use this when you have it.
        - Email (contains "@"):        exact email search.
        - Any other string:            compound text search (name, username, etc.) — may
                                       return multiple candidates if the name is ambiguous.

        If multiple persons match a name search, returns PersonAmbiguousResult with
        candidate list so you can call again with the exact person_id UUID.

        Args:
            identifier: Person UUID, email address, or display name / username.
                        Prefer UUID when available — it is the fastest lookup path.

        Returns:
            PersonDetail with id, type, display_name, email, team, labels, note.
            Or PersonAmbiguousResult if multiple name matches are found.
        """
        return await _resolve_person(ctx, identifier)

    def _person_detail(data: dict[str, Any]) -> PersonDetail:
        return PersonDetail(
            id=data.get("id", ""),
            display_name=data.get("displayName"),
            person_type=data.get("personType"),
            email=data.get("email"),
            phone=data.get("phone"),
            username=data.get("username"),
            team_id=data.get("teamId"),
            labels=[str(lbl) for lbl in data.get("labels", [])],
            note=data.get("note"),
            authorization_role=data.get("authorizationRole"),
            source_id=data.get("sourceId"),
            source_url=data.get("sourceUrl"),
            gui_url=_gui_url("persons", data.get("id", "")),
            next_steps=[
                "Call search_conversations(assignee_person_id='<id>') to see their conversations.",
                "Call search_persons() to find other persons.",
            ],
        )

    # ------------------------------------------------------------------
    # Tool 9b — get_persons (batch)
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Get Persons (Batch)",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def get_persons(
        ctx: Context,
        identifiers: list[str],
    ) -> PersonBatchResult:
        """Fetch full details for multiple persons in a single parallel call.

        Equivalent to calling get_person() for each identifier, but all lookups
        run concurrently. Ideal when debugging a conversation with several
        participants — avoids N sequential round-trips.

        Each identifier uses the same resolution strategy as get_person():
        - UUID: fastest, direct GET.
        - Email (contains "@"): exact email search.
        - Any other string: compound name/username search.

        Args:
            identifiers: List of person UUIDs, emails, or display names. Max 20.
                         Prefer UUIDs for speed. Use get_person() for single lookups.

        Returns:
            PersonBatchResult with one entry per identifier. Each entry has either
            a result (PersonDetail or PersonAmbiguousResult) or an error string.
        """
        capped = identifiers[:20]
        await _ctx_log(ctx, f"Batch-looking up {len(capped)} persons")

        async def _single(ident: str) -> PersonBatchEntry:
            try:
                result = await _resolve_person(ctx, ident)
                return PersonBatchEntry(identifier=ident, result=result)
            except ToolError as exc:
                return PersonBatchEntry(identifier=ident, error=str(exc))

        entries = list(await asyncio.gather(*[_single(i) for i in capped]))
        succeeded = sum(1 for e in entries if e.error is None)
        return PersonBatchResult(
            entries=entries,
            total=len(entries),
            succeeded=succeeded,
            failed=len(entries) - succeeded,
            next_steps=[
                "For entries with error, try get_person() with a more specific identifier.",
                "For PersonAmbiguousResult entries, call get_person(identifier='<uuid>') with the exact UUID.",
            ],
        )

    # ------------------------------------------------------------------
    # Tool 10 — search_users
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Search Users",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def search_users(
        ctx: Context,
        query: str | None = None,
        offset: int = 0,
        limit: int = 25,
        fields: list[str] | None = None,
    ) -> UserPage:
        """Search Unblu admin-level user accounts.

        Users are the Unblu administrator/operator accounts (not real-time participants).
        For conversation participants (agents/visitors/bots), use search_persons() instead.

        Args:
            query: Free-text search across username, display name, email.
            offset: Page offset for pagination (default 0).
            limit: Number of users to return (default 25).
            fields: Optional list of field names to include per item (e.g. ["id",
                    "username"]). When set, items are filtered dicts instead of
                    full UserSummary objects, reducing token usage.

        Returns:
            Paginated list of users with id, username, display_name, email, role.
        """
        await _ctx_log(ctx, f"Searching users (query={query}, offset={offset})")

        search_filters: list[dict[str, Any]] = []
        if query:
            search_filters.append({
                "$_type": "CompoundUserSearchFilter",
                "field": "COMPOUND",
                "operator": {
                    "$_type": "StringOperator",
                    "type": "CONTAINS",
                    "value": query,
                },
            })

        body = build_query_body(
            offset=offset,
            limit=limit,
            search_filters=search_filters or None,
            query_type="UserQuery",
        )

        status_code, data = await _request("POST", "/users/search", body=body)
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = f"User search failed (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
            raise ToolError(msg)

        has_more, next_offset_val = parse_pagination(data)
        raw_items: list[dict[str, Any]] = data.get("items", [])

        if fields:
            items: list[Any] = [_filter_fields(u, fields) for u in raw_items]
        else:
            items = [
                UserSummary(
                    id=u.get("id", ""),
                    username=u.get("username"),
                    display_name=u.get("displayName"),
                    email=u.get("email"),
                    authorization_role=u.get("authorizationRole"),
                )
                for u in raw_items
            ]

        next_steps = ["Call get_user(identifier='<id>') for full user details."]
        if has_more:
            next_steps.append(f"Call search_users(offset={next_offset_val}) to get the next page.")

        return UserPage(
            items=items,
            has_more=has_more,
            next_offset=next_offset_val,
            next_steps=next_steps,
        )

    # ------------------------------------------------------------------
    # Tool 11 — get_user
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Get User",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def get_user(
        ctx: Context,
        identifier: str,
    ) -> UserDetail:
        """Get full details of an Unblu user account by UUID, username, or email.

        Resolution strategy (fastest to slowest):
        - UUID (e.g. "a1b2c3d4-..."): direct GET — fastest, use this when you have it.
        - Username (no "@"):           direct GET by username.
        - Email (contains "@"):        search by email (POST search).

        For real-time session participants (agents/visitors), use get_person() instead.

        Args:
            identifier: User UUID, username, or email address.
                        Prefer UUID or username when available — they are the fastest lookup paths.

        Returns:
            UserDetail with id, username, display_name, email, role, team.
        """
        await _ctx_log(ctx, f"Looking up user: {identifier}")

        # UUID direct lookup (fastest)
        if _UUID_RE.match(identifier):
            status_code, data = await _request("GET", f"/users/{identifier}")
            if status_code == _HTTP_NOT_FOUND:
                msg = f"User '{identifier}' not found. Call search_users() to browse available users. [PERMANENT]"
                raise ToolError(msg)
            if status_code >= _HTTP_CLIENT_ERROR:
                msg = f"Failed to fetch user (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
                raise ToolError(msg)
            return _user_detail(data)

        # Email → search
        if "@" in identifier:
            body = build_query_body(
                offset=0,
                limit=5,
                search_filters=[
                    {
                        "$_type": "EmailUserSearchFilter",
                        "field": "EMAIL",
                        "operator": {
                            "$_type": "StringOperator",
                            "type": "EQUALS",
                            "value": identifier,
                        },
                    }
                ],
                query_type="UserQuery",
            )
            status_code, data = await _request("POST", "/users/search", body=body)
            items: list[dict[str, Any]] = data.get("items", []) if status_code < _HTTP_CLIENT_ERROR else []
            if items:
                return _user_detail(items[0])
            msg = f"No user found with email '{identifier}'. Call search_users() to browse available users. [PERMANENT]"
            raise ToolError(msg)

        # Username lookup (direct GET)
        status_code, data = await _request("GET", "/users/getByUsername", query_params={"username": identifier})
        if status_code == _HTTP_NOT_FOUND:
            msg = f"No user found with username '{identifier}'. Call search_users(query='{identifier}') to search more broadly. [PERMANENT]"
            raise ToolError(msg)
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = f"Failed to fetch user (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
            raise ToolError(msg)
        return _user_detail(data)

    def _user_detail(data: dict[str, Any]) -> UserDetail:
        return UserDetail(
            id=data.get("id", ""),
            username=data.get("username"),
            display_name=data.get("displayName"),
            email=data.get("email"),
            phone=data.get("phone"),
            team_id=data.get("teamId"),
            authorization_role=data.get("authorizationRole"),
            virtual_user=data.get("virtualUser"),
            externally_managed=data.get("externallyManaged"),
            gui_url=_gui_url("users", data.get("id", "")),
            next_steps=[
                "Call search_users() to find other users.",
                "Call search_persons() to find real-time session participants.",
            ],
        )

    # ------------------------------------------------------------------
    # Tool 12 — check_agent_availability
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Check Agent Availability",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def check_agent_availability(
        ctx: Context,
        named_area_site_id: str | None = None,
    ) -> AvailabilityInfo:
        """Check agent availability in Unblu — who is online and able to handle conversations.

        Args:
            named_area_site_id: Optional named area / site ID to filter availability
                                by a specific area. Leave empty for account-wide availability.
                                Use find_operation("named areas") to discover named area IDs.

        Returns:
            Availability status and raw availability data from the Unblu API.
        """
        await _ctx_log(ctx, f"Checking agent availability (named_area={named_area_site_id})")
        params: dict[str, Any] = {}
        if named_area_site_id:
            params["namedAreaSiteId"] = named_area_site_id

        status_code, data = await _request("GET", "/availability/getAgentAvailability", query_params=params or None)
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = f"Failed to get agent availability (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
            raise ToolError(msg)

        return AvailabilityInfo(
            named_area_site_id=named_area_site_id,
            availability=data.get("agentAvailability") or data.get("availability"),
            raw=data,
            next_steps=[
                "Call search_persons(person_type='AGENT') to list active agents.",
                "Call search_conversations(status='QUEUED') to see waiting conversations.",
            ],
        )

    # ------------------------------------------------------------------
    # Tool 13 — search_named_areas  (bonus: named areas are key for debugging)
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Search Named Areas",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def search_named_areas(
        ctx: Context,
        query: str | None = None,
        offset: int = 0,
        limit: int = 25,
    ) -> ExecuteResult:
        """Search Unblu named areas (routing targets for conversations).

        Named areas are the primary way conversations are routed to queues.
        Their IDs are needed for check_agent_availability() and search_conversations().

        Args:
            query: Optional text to filter named areas by name.
            offset: Page offset for pagination (default 0).
            limit: Number of named areas to return (default 25).

        Returns:
            List of named areas with id, name, and site ID.
        """
        await _ctx_log(ctx, f"Searching named areas (query={query}, offset={offset})")
        search_filters: list[dict[str, Any]] = []
        if query:
            search_filters.append({
                "$_type": "NamedAreaSearchFilter",
                "field": "COMPOUND",
                "operator": {
                    "$_type": "StringOperator",
                    "type": "CONTAINS",
                    "value": query,
                },
            })

        body = build_query_body(
            offset=offset,
            limit=limit,
            search_filters=search_filters or None,
            query_type="NamedAreaQuery",
        )

        status_code, data = await _request("POST", "/namedAreas/search", body=body)
        if status_code >= _HTTP_CLIENT_ERROR:
            msg = f"Named area search failed (HTTP {status_code}): {str(data)[:200]}{_error_hint(status_code)}"
            raise ToolError(msg)

        has_more, next_offset_val = parse_pagination(data)
        items = data.get("items", [])
        data_out: dict[str, Any] = {
            "items": [
                {
                    "id": a.get("id"),
                    "name": a.get("name"),
                    "site_id": a.get("siteId"),
                }
                for a in items
            ]
        }

        next_steps: list[str] = [
            "Use the 'id' as named_area_site_id in check_agent_availability().",
        ]
        if has_more:
            next_steps.append(f"Call search_named_areas(offset={next_offset_val}) for the next page.")

        return ExecuteResult(
            status_code=status_code,
            data=data_out,
            has_more=has_more,
            next_offset=next_offset_val,
            next_steps=next_steps,
        )

    # ------------------------------------------------------------------
    # Health check helpers (used by check_deployment_health)
    # ------------------------------------------------------------------

    async def _check_connectivity() -> HealthCheck:
        try:
            status_code, data = await _request("GET", "/accounts/getCurrentAccount")
            if status_code >= _HTTP_CLIENT_ERROR:
                return HealthCheck(
                    name="connectivity",
                    status="ERROR",
                    message=f"HTTP {status_code} — verify UNBLU_BASE_URL, UNBLU_API_KEY, or credentials.",
                )
            return HealthCheck(
                name="connectivity",
                status="OK",
                message=f"Connected to '{data.get('name') or data.get('id', '?')}'",
                details=[{"account_id": data.get("id"), "account_name": data.get("name")}],
            )
        except Exception as e:
            return HealthCheck(name="connectivity", status="ERROR", message=f"Connection failed: {e}")

    LICENSE_EXPIRY_WARN_DAYS = 30
    LICENSE_VALID_STATES = {"ACTIVE", "VALID"}

    async def _check_license() -> HealthCheck:
        try:
            status_code, data = await _request("GET", "/global/read")
            if status_code >= _HTTP_CLIENT_ERROR:
                return HealthCheck(name="license", status="WARN", message=f"Could not read global settings (HTTP {status_code}).")
            lic = data.get("currentLicense") or {}
            state = lic.get("state", "UNKNOWN")
            server_id = data.get("serverIdentifier", "?")
            expiry_ms = lic.get("expirationTimestamp")
            expiry_msg = ""
            check_status = "OK"
            if expiry_ms is not None:
                days_left = (expiry_ms / 1000 - time.time()) / 86400
                if days_left < 0:
                    check_status = "ERROR"
                    expiry_msg = f" — EXPIRED {abs(int(days_left))}d ago"
                elif days_left < LICENSE_EXPIRY_WARN_DAYS:
                    check_status = "WARN"
                    expiry_msg = f" — expires in {int(days_left)}d"
                else:
                    expiry_msg = f" — expires in {int(days_left)}d"
            if state not in LICENSE_VALID_STATES and check_status == "OK":
                check_status = "WARN"
            return HealthCheck(
                name="license",
                status=check_status,
                message=f"License: {state}{expiry_msg} | Server: {server_id}",
                details=[
                    {
                        "server_identifier": server_id,
                        "license_state": state,
                        "license_id": lic.get("licenseId"),
                        "expiration_timestamp_ms": expiry_ms,
                    }
                ],
            )
        except Exception as e:
            return HealthCheck(name="license", status="WARN", message=f"Could not read license: {e}")

    async def _check_product_version() -> HealthCheck:
        try:
            status_code, data = await _request("GET", "/global/productVersion")
            if status_code >= _HTTP_CLIENT_ERROR:
                return HealthCheck(name="product_version", status="WARN", message=f"Could not read product version (HTTP {status_code}).")
            version = data.get("version") or data.get("productVersion") or json.dumps(data)[:100]
            return HealthCheck(
                name="product_version",
                status="OK",
                message=f"Version: {version}",
                details=[data],
            )
        except Exception as e:
            return HealthCheck(name="product_version", status="WARN", message=f"Could not read product version: {e}")

    async def _check_bots() -> HealthCheck:
        try:
            status_code, data = await _request(
                "POST",
                "/bots/search",
                body=build_query_body(offset=0, limit=100, query_type="DialogBotQuery"),
            )
            if status_code >= _HTTP_CLIENT_ERROR:
                return HealthCheck(name="bots", status="WARN", message=f"Could not list bots (HTTP {status_code}).")
            items: list[dict[str, Any]] = data.get("items", [])
            if not items:
                return HealthCheck(name="bots", status="OK", message="No dialog bots configured.")
            details = [
                {
                    "name": b.get("name"),
                    "id": b.get("id"),
                    "webhook_status": b.get("webhookStatus"),
                    "webhook_endpoint": b.get("webhookEndpoint"),
                }
                for b in items
            ]
            inactive = [d for d in details if d["webhook_status"] not in {"ACTIVE", None}]
            if inactive:
                names = ", ".join(str(d["name"] or d["id"]) for d in inactive)
                return HealthCheck(
                    name="bots",
                    status="WARN",
                    message=f"{len(items)} bots found — {len(inactive)} not ACTIVE: {names}",
                    details=details,
                )
            return HealthCheck(
                name="bots",
                status="OK",
                message=f"{len(items)} bot(s) — all ACTIVE",
                details=details,
            )
        except Exception as e:
            return HealthCheck(name="bots", status="WARN", message=f"Could not check bots: {e}")

    async def _check_webhooks() -> HealthCheck:
        try:
            status_code, data = await _request(
                "POST",
                "/webhookregistrations/search",
                body=build_query_body(offset=0, limit=100, query_type="WebhookRegistrationQuery"),
            )
            if status_code >= _HTTP_CLIENT_ERROR:
                return HealthCheck(name="webhooks", status="WARN", message=f"Could not list webhook registrations (HTTP {status_code}).")
            items = data.get("items", [])
            if not items:
                return HealthCheck(name="webhooks", status="OK", message="No webhook registrations configured.")
            details = [
                {
                    "name": w.get("name"),
                    "id": w.get("id"),
                    "api_version": w.get("apiVersion"),
                    "endpoint": w.get("endpoint"),
                }
                for w in items
            ]
            return HealthCheck(
                name="webhooks",
                status="OK",
                message=f"{len(items)} webhook registration(s)",
                details=details,
            )
        except Exception as e:
            return HealthCheck(name="webhooks", status="WARN", message=f"Could not check webhooks: {e}")

    async def _check_interceptors() -> HealthCheck:
        try:
            status_code, data = await _request(
                "POST",
                "/messageinterceptors/search",
                body=build_query_body(offset=0, limit=100, query_type="MessageInterceptorQuery"),
            )
            if status_code >= _HTTP_CLIENT_ERROR:
                return HealthCheck(name="interceptors", status="WARN", message=f"Could not list interceptors (HTTP {status_code}).")
            items = data.get("items", [])
            if not items:
                return HealthCheck(name="interceptors", status="OK", message="No message interceptors configured.")
            details = [
                {
                    "name": ic.get("name"),
                    "id": ic.get("id"),
                    "webhook_status": ic.get("webhookStatus"),
                    "webhook_endpoint": ic.get("webhookEndpoint"),
                }
                for ic in items
            ]
            inactive = [d for d in details if d["webhook_status"] not in {"ACTIVE", None}]
            if inactive:
                names = ", ".join(str(d["name"] or d["id"]) for d in inactive)
                return HealthCheck(
                    name="interceptors",
                    status="WARN",
                    message=f"{len(items)} interceptors — {len(inactive)} not ACTIVE: {names}",
                    details=details,
                )
            return HealthCheck(
                name="interceptors",
                status="OK",
                message=f"{len(items)} interceptor(s) — all ACTIVE",
                details=details,
            )
        except Exception as e:
            return HealthCheck(name="interceptors", status="WARN", message=f"Could not check interceptors: {e}")

    async def _check_availability() -> HealthCheck:
        try:
            status_code, data = await _request("GET", "/availability/getAgentAvailability")
            if status_code >= _HTTP_CLIENT_ERROR:
                return HealthCheck(name="availability", status="WARN", message=f"Could not check agent availability (HTTP {status_code}).")
            avail = data.get("agentAvailability") or data.get("availability", "UNKNOWN")
            check_status = "OK" if avail == "AVAILABLE" else "WARN"
            return HealthCheck(
                name="availability",
                status=check_status,
                message=f"Agent availability: {avail}",
                details=[data],
            )
        except Exception as e:
            return HealthCheck(name="availability", status="WARN", message=f"Could not check availability: {e}")

    # ------------------------------------------------------------------
    # Tool 14 — check_deployment_health
    # ------------------------------------------------------------------

    @mcp.tool(
        annotations={
            "title": "Check Deployment Health",
            "readOnlyHint": True,
            "openWorldHint": False,
        },
    )
    async def check_deployment_health(
        ctx: Context,
    ) -> DeploymentHealthReport:
        """Check the health of the Unblu deployment in a single call.

        Runs seven checks in parallel:
        - connectivity:     confirms API connectivity and identifies the account
        - license:          reads license state and expiry from /global/read
        - product_version:  reports the installed Unblu version
        - bots:             lists dialog bots and checks webhookStatus (ACTIVE = healthy)
        - webhooks:         lists webhook registrations (informational — endpoint + apiVersion)
        - interceptors:     lists message interceptors and checks webhookStatus
        - availability:     checks account-wide agent availability

        Returns:
            DeploymentHealthReport with overall_status (OK/WARN/ERROR), per-check
            results, and actionable next_steps for any failing checks.
        """
        await _ctx_log(ctx, "Running deployment health checks (7 checks in parallel)")
        await provider.ensure_connection()
        check_results: list[HealthCheck] = list(
            await asyncio.gather(
                _check_connectivity(),
                _check_license(),
                _check_product_version(),
                _check_bots(),
                _check_webhooks(),
                _check_interceptors(),
                _check_availability(),
            )
        )

        ok_count = sum(1 for c in check_results if c.status == "OK")
        warn_count = sum(1 for c in check_results if c.status == "WARN")
        error_count = sum(1 for c in check_results if c.status == "ERROR")

        if error_count > 0:
            overall = "ERROR"
        elif warn_count > 0:
            overall = "WARN"
        else:
            overall = "OK"

        next_steps: list[str] = []
        for c in check_results:
            if c.status == "ERROR":
                next_steps.append(f"[ERROR:{c.name}] {c.message}")
            elif c.status == "WARN":
                next_steps.append(f"[WARN:{c.name}] {c.message}")
        if not next_steps:
            next_steps = [
                "All checks passed.",
                "Call search_conversations(status='QUEUED') to see waiting conversations.",
                "Call search_conversations(status='ACTIVE') to see live conversations.",
            ]

        return DeploymentHealthReport(
            overall_status=overall,
            checks=check_results,
            ok_count=ok_count,
            warn_count=warn_count,
            error_count=error_count,
            next_steps=next_steps,
        )

    # ------------------------------------------------------------------
    # Prompts — debugging workflow fast-paths
    # ------------------------------------------------------------------

    @mcp.prompt()
    def debug_conversation(conversation_id: str) -> str:
        """Step-by-step debugging workflow for a specific conversation."""
        return (
            f"Debug conversation {conversation_id} step by step:\n\n"
            f"1. Call get_conversation(conversation_id='{conversation_id}') to get full details.\n"
            "2. For each participant in the response, call get_person(identifier='<personId>') "
            "to inspect their state, type, labels, and note.\n"
            "3. Check agent availability with check_agent_availability() "
            "to see if agents are online.\n"
            "4. If the conversation state seems wrong (e.g. QUEUED with no agents), "
            "report the issue with the details you found.\n"
            "5. If needed to reset: assign_conversation() to reassign or "
            "end_conversation() to close.\n\n"
            "Summarise: conversation state, assignee, participant types, awaited_person_type, "
            "and any anomalies found."
        )

    @mcp.prompt()
    def find_agent(identifier: str) -> str:
        """Debugging workflow to locate and inspect an agent."""
        return (
            f"Locate and inspect agent '{identifier}':\n\n"
            f"1. Call get_person(identifier='{identifier}') — accepts UUID, email, or name.\n"
            "2. Note the person_type (should be AGENT), team_id, and authorization_role.\n"
            "3. Call search_conversations(assignee_person_id='<id>') to see "
            "their current and recent conversations.\n"
            "4. Call check_agent_availability() to see account-wide agent status.\n\n"
            "Summarise: agent found or not, their state, assigned conversations, "
            "and any anomalies."
        )

    @mcp.prompt()
    def account_health_check() -> str:
        """Debugging workflow for an account-wide health overview."""
        return (
            "Perform an Unblu account health check:\n\n"
            "1. Call get_current_account() — confirm connectivity and account identity.\n"
            "2. Call check_agent_availability() — are agents online?\n"
            "3. Call search_conversations(status='QUEUED', limit=10) "
            "— any conversations waiting without an agent?\n"
            "4. Call search_conversations(status='ACTIVE', limit=10) "
            "— how many active conversations right now?\n"
            "5. If queued conversations exist and availability is low, flag this.\n\n"
            "Summarise: account name, agent availability, queued count, "
            "active count, and any anomalies."
        )

    return mcp

detect_environment_from_context

detect_environment_from_context() -> str | None

Detect the environment from the current kubectl context.

Matches environment names from the loaded configuration against patterns in the current kubectl context name.

Returns:

  • str | None

    Environment name or None if not detected.

Source code in src/unblu_mcp/_internal/providers_k8s.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def detect_environment_from_context() -> str | None:
    """Detect the environment from the current kubectl context.

    Matches environment names from the loaded configuration against
    patterns in the current kubectl context name.

    Returns:
        Environment name or None if not detected.
    """
    try:
        result = subprocess.run(
            ["kubectl", "config", "current-context"],  # noqa: S607
            capture_output=True,
            text=True,
            check=True,
            timeout=5,  # 5 second timeout to avoid hanging
        )
        context = result.stdout.strip()

        # Match against configured environment names
        environments = _get_default_environments()
        for env in environments:
            if f"-{env}-" in context or context.endswith(f"-{env}"):
                return env
        return None  # noqa: TRY300
    except subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired:
        return None

get_parser

get_parser() -> ArgumentParser

Return the CLI argument parser.

Returns:

Source code in src/unblu_mcp/_internal/cli.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def get_parser() -> argparse.ArgumentParser:
    """Return the CLI argument parser.

    Returns:
        An argparse parser.
    """
    parser = argparse.ArgumentParser(
        prog="unblu-mcp",
        description="Unblu MCP Server — deployment health checks, conversation ops, and 300+ API endpoints",
    )
    parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {debug._get_version()}")
    parser.add_argument("--debug-info", action=_DebugInfo, help="Print debug information.")
    parser.add_argument(
        "--print-k8s-config-template",
        action=_PrintK8sConfigTemplate,
        help="Print a sample k8s_environments.yaml template and exit.",
    )
    parser.add_argument(
        "--spec",
        type=str,
        default=None,
        help="Path to swagger.json OpenAPI spec file.",
    )
    parser.add_argument(
        "--provider",
        type=str,
        choices=["default", "k8s"],
        default="default",
        help="Connection provider to use (default: default).",
    )
    parser.add_argument(
        "--environment",
        type=str,
        default="dev",
        help="K8s environment name (only with --provider k8s). Default: dev.",
    )
    parser.add_argument(
        "--k8s-config",
        type=str,
        default=None,
        help="Path to K8s environments YAML config file (only with --provider k8s).",
    )
    return parser

get_server

get_server(**kwargs: Any) -> FastMCP

Get (or create) the singleton Unblu MCP server instance.

Source code in src/unblu_mcp/_internal/server.py
2117
2118
2119
def get_server(**kwargs: Any) -> FastMCP:
    """Get (or create) the singleton Unblu MCP server instance."""
    return _ServerHolder.get(**kwargs)

main

main(args: list[str] | None = None) -> int

Run the main program.

This function is executed when you type unblu-mcp or python -m unblu_mcp.

Parameters:

  • args (list[str] | None, default: None ) –

    Arguments passed from the command line.

Returns:

  • int

    An exit code.

Source code in src/unblu_mcp/_internal/cli.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def main(args: list[str] | None = None) -> int:
    """Run the main program.

    This function is executed when you type `unblu-mcp` or `python -m unblu_mcp`.

    Parameters:
        args: Arguments passed from the command line.

    Returns:
        An exit code.
    """
    parser = get_parser()
    if args == []:
        parser.print_help()
        return 0
    opts = parser.parse_args(args=args)

    provider = _get_provider(opts.provider, opts.environment, opts.k8s_config)
    server = _create_server(spec_path=opts.spec, provider=provider)
    try:
        server.run()
    except ConfigurationError as e:
        print(f"\n❌ Configuration Error: {e}\n", file=sys.stderr)  # noqa: T201
        return 1
    return 0

make_enum_filter

make_enum_filter(
    field: str,
    value: str,
    filter_type: str = "ConversationStateSearchFilter",
    operator_type: str = "EConversationStateOperator",
) -> dict[str, Any]

Build an Unblu enum equality search filter.

Source code in src/unblu_mcp/_internal/pagination.py
78
79
80
81
82
83
84
85
86
87
88
89
def make_enum_filter(
    field: str,
    value: str,
    filter_type: str = "ConversationStateSearchFilter",
    operator_type: str = "EConversationStateOperator",
) -> dict[str, Any]:
    """Build an Unblu enum equality search filter."""
    return {
        "$_type": filter_type,
        "field": field,
        "operator": {"$_type": operator_type, "type": "EQUALS", "value": value},
    }

make_id_filter

make_id_filter(field: str, value: str) -> dict[str, Any]

Build an Unblu ID equality search filter.

Source code in src/unblu_mcp/_internal/pagination.py
69
70
71
72
73
74
75
def make_id_filter(field: str, value: str) -> dict[str, Any]:
    """Build an Unblu ID equality search filter."""
    return {
        "$_type": "IdSearchFilter",
        "field": field,
        "operator": {"$_type": "IdOperator", "type": "EQUALS", "value": value},
    }

make_string_filter

make_string_filter(
    field: str, value: str, operator: str = "EQUALS"
) -> dict[str, Any]

Build an Unblu string equality search filter.

Parameters:

  • field (str) –

    The EConversationSearchFilterField / EPersonSearchFilterField value.

  • value (str) –

    The value to match.

  • operator (str, default: 'EQUALS' ) –

    String operator (EQUALS, CONTAINS, STARTS_WITH, etc.).

Returns:

Source code in src/unblu_mcp/_internal/pagination.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def make_string_filter(field: str, value: str, operator: str = "EQUALS") -> dict[str, Any]:
    """Build an Unblu string equality search filter.

    Args:
        field: The EConversationSearchFilterField / EPersonSearchFilterField value.
        value: The value to match.
        operator: String operator (EQUALS, CONTAINS, STARTS_WITH, etc.).

    Returns:
        SearchFilter dict.
    """
    return {
        "$_type": "StringSearchFilter",
        "field": field,
        "operator": {"$_type": "StringOperator", "type": operator, "value": value},
    }

parse_pagination

parse_pagination(
    result: dict[str, Any],
) -> tuple[bool, int | None]

Extract pagination info from an Unblu search result.

Parameters:

  • result (dict[str, Any]) –

    Raw JSON response from an Unblu search endpoint.

Returns:

  • tuple[bool, int | None]

    Tuple of (has_more, next_offset). next_offset is None when has_more is False.

Source code in src/unblu_mcp/_internal/pagination.py
37
38
39
40
41
42
43
44
45
46
47
48
def parse_pagination(result: dict[str, Any]) -> tuple[bool, int | None]:
    """Extract pagination info from an Unblu search result.

    Args:
        result: Raw JSON response from an Unblu search endpoint.

    Returns:
        Tuple of (has_more, next_offset). next_offset is None when has_more is False.
    """
    has_more = bool(result.get("hasMoreItems"))
    next_offset: int | None = result.get("nextOffset") if has_more else None
    return has_more, next_offset