Skip to main content
Glama
wpfleger96

PagerDuty MCP Server

by wpfleger96

build_user_context

Builds a dictionary with user, team, service, and escalation policy IDs from the current user's context to filter PagerDuty resources.

Instructions

Validate and build the current user's context into a dictionary with the following format: { "user_id": str, "team_ids": List[str], "service_ids": List[str], "escalation_policy_ids": List[str] } The MCP server tools use this user context to filter the following resources: - Escalation policies - Incidents - Oncalls - Services - Users

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core implementation of build_user_context. Fetches the current PagerDuty user via _show_current_user(), then builds a context dict containing user_id, name, email, team_ids (from teams.fetch_team_ids), service_ids (from services.fetch_service_ids), and escalation_policy_ids (from escalation_policies.fetch_escalation_policy_ids). Includes error handling via utils.handle_api_error.
    async def build_user_context() -> Dict[str, Any]:
        """Validate and build the current user's context. Exposed as MCP server tool.
    
        See the "Standard Response Format" section in `tools.md` for the complete standard response structure.
    
        Returns:
            See the "Standard Response Format" section in `tools.md` for the complete standard response structure.
            The response will contain the current user's context in the format defined in the "build_user_context" section of `tools.md`.
    
        Raises:
            See the "Error Handling" section in `tools.md` for common error scenarios.
        """
        try:
            user = await _show_current_user()
            if not user:
                raise ValueError("Failed to get current user data")
    
            context = {
                "user_id": str(user.get("id", "")).strip(),
                "name": user.get("name", ""),
                "email": user.get("email", ""),
                "team_ids": [],
                "service_ids": [],
                "escalation_policy_ids": [],
            }
    
            if not context["user_id"]:
                raise ValueError("Invalid user data: missing or empty user ID")
    
            team_ids = teams.fetch_team_ids(user=user)
            context["team_ids"] = [
                str(tid).strip() for tid in team_ids if tid and str(tid).strip()
            ]
    
            if context["team_ids"]:
                service_ids = await services.fetch_service_ids(team_ids=context["team_ids"])
                context["service_ids"] = [
                    str(sid).strip() for sid in service_ids if sid and str(sid).strip()
                ]
    
            escalation_policy_ids = await escalation_policies.fetch_escalation_policy_ids(
                user_id=context["user_id"]
            )
            context["escalation_policy_ids"] = [
                str(epid).strip()
                for epid in escalation_policy_ids
                if epid and str(epid).strip()
            ]
    
            return context
    
        except Exception as e:
            utils.handle_api_error(e)
  • MCP tool registration for build_user_context. Decorated with @mcp.tool() and @tool_error_boundary, delegates directly to users.build_user_context().
    @mcp.tool()
    @tool_error_boundary
    async def build_user_context() -> Dict[str, Any]:
        """Validate and build the current user's context into a dictionary with the following format:
            {
                "user_id": str,
                "team_ids": List[str],
                "service_ids": List[str],
                "escalation_policy_ids": List[str]
            }
        The MCP server tools use this user context to filter the following resources:
            - Escalation policies
            - Incidents
            - Oncalls
            - Services
            - Users
        """
        return await users.build_user_context()
  • Return type definition/schema of build_user_context. Returns a dict with keys: user_id (str), name (str), email (str), team_ids (List[str]), service_ids (List[str]), escalation_policy_ids (List[str]).
    context = {
        "user_id": str(user.get("id", "")).strip(),
        "name": user.get("name", ""),
        "email": user.get("email", ""),
        "team_ids": [],
        "service_ids": [],
        "escalation_policy_ids": [],
    }
  • Private helper _show_current_user() called by build_user_context. Calls PagerDuty API GET /users/me to retrieve the current user's profile, validates the response has an 'id', and returns the parsed user dict.
    async def _show_current_user() -> Dict[str, Any]:
        """Get the current user's PagerDuty profile including their teams, contact methods, and notification rules.
    
        Returns:
            See the "Standard Response Format" section in `tools.md` for the complete standard response structure.
            The response will contain a single user with detailed profile information including teams, contact methods, and notification rules.
    
        Raises:
            See the "Error Handling" section in `tools.md` for common error scenarios.
        """
        pd_client = create_client()
        try:
            result = await safe_execute_async(
                lambda: pd_client.jget(USERS_URL + "/me"), "fetch current user"
            )
            response = result["user"]
            user = {}
            if response:
                model = User.model_validate(response)
                user = model.to_clean_dict()
            if not user or "id" not in user or not user["id"]:
                raise ValueError("Invalid user object: missing ID")
            return user
        except Exception as e:
            utils.handle_api_error(e)
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description should disclose behavior. It says 'validate and build' but does not explain side effects, permissions, or error cases. It provides minimal insight into what the tool does beyond returning a dictionary.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences: one gives the output format, the other explains its purpose. No wasted words, information is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the basic purpose and output format and mentions how the context is used. It does not explain validation behavior or error handling, but given the presence of an output schema (not shown), it is reasonably complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has no parameters; schema coverage is trivially 100%. The description adds the output format, which is useful, but does not explain why no parameters are needed or how context is derived (e.g., from authentication). Baselined at 4 due to zero params, but lacks deeper explanation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool builds user context into a specific dictionary format. It distinguishes from sibling tools, which are action-oriented or retrieval tools, by being a context-preparation step.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies this tool is used before other tools to filter resources, but it does not explicitly state when to use it, when not to, or provide alternatives. It lacks clear usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/wpfleger96/pagerduty-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server