How to integrate Gitlab MCP with Pydantic AI

Connect Pydantic AI to Gitlab MCP. Create new gitlab group for qa team, open bug issue in frontend project, and more using natural language, with authentication handled for you.

Gitlab logoGitlab
Oauth2

Gitlab is a web-based DevOps platform for managing source code, issues, and CI/CD pipelines. It streamlines software development with integrated collaboration and automation tools.

123 Tools

Introduction

This guide walks you through connecting Gitlab to Pydantic AI using the Composio tool router. By the end, you'll have a working Gitlab agent that can create new gitlab group for qa team, open bug issue in frontend project, create branch from latest main commit through natural language commands.

This guide will help you understand how to give your Pydantic AI agent real control over a Gitlab account through Composio's Gitlab MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Gitlab with

TL;DR

Here's what you'll learn:
  • How to set up your Composio API key and User ID
  • How to create a Composio Tool Router session for Gitlab
  • How to attach an MCP Server to a Pydantic AI agent
  • How to stream responses and maintain chat history
  • How to build a simple REPL-style chat interface to test your Gitlab workflows

What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.

Key features include:

  • Type Safety: Built on Pydantic for automatic data validation
  • MCP Support: Native support for Model Context Protocol servers
  • Streaming: Built-in support for streaming responses
  • Async First: Designed for async/await patterns

What is the Gitlab MCP server, and what's possible with it?

The Gitlab MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Gitlab account. It provides structured and secure access to your repositories, projects, and issues, so your agent can perform actions like creating projects, managing issues, handling branches, and automating DevOps workflows on your behalf.

  • Project and group automation: Instantly create new Gitlab projects or organize your workspaces by setting up project groups—all without manual clicks.
  • Issue creation and tracking: Have your agent report bugs, request features, or open new issues in specific projects to keep your team on top of tasks.
  • Branch management: Let your agent create repository branches from any commit or base branch, making it easy to streamline your development process.
  • Project lifecycle management: Archive completed projects or delete unneeded ones, keeping your workspace clean and up to date with minimal effort.
  • Commit and job insights: Retrieve commit references, determine commit sequence in project history, or erase job artifacts and logs for deeper CI/CD control.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

Before starting, make sure you have:
  • Python 3.9 or higher
  • A Composio account with an active API key
  • Basic familiarity with Python and async programming
2

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.
3

Install dependencies

bash
pip install composio pydantic-ai python-dotenv

Install the required libraries.

What's happening:

  • composio connects your agent to external SaaS tools like Gitlab
  • pydantic-ai lets you create structured AI agents with tool support
  • python-dotenv loads your environment variables securely from a .env file
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your agent to Composio's API
  • USER_ID associates your session with your account for secure tool access
  • OPENAI_API_KEY to access OpenAI LLMs
5

Import dependencies

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
What's happening:
  • We load environment variables and import required modules
  • Composio manages connections to Gitlab
  • MCPServerStreamableHTTP connects to the Gitlab MCP server endpoint
  • Agent from Pydantic AI lets you define and run the AI assistant
6

Create a Tool Router Session

python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Gitlab
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["gitlab"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
What's happening:
  • We're creating a Tool Router session that gives your agent access to Gitlab tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use
7

Initialize the Pydantic AI Agent

python
# Attach the MCP server to a Pydantic AI Agent
gitlab_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[gitlab_mcp],
    instructions=(
        "You are a Gitlab assistant. Use Gitlab tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
What's happening:
  • The MCP client connects to the Gitlab endpoint
  • The agent uses GPT-5 to interpret user commands and perform Gitlab operations
  • The instructions field defines the agent's role and behavior
8

Build the chat interface

python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Gitlab.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
What's happening:
  • The agent reads input from the terminal and streams its response
  • Gitlab API calls happen automatically under the hood
  • The model keeps conversation history to maintain context across turns
9

Run the application

python
if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • The asyncio loop launches the agent and keeps it running until you exit

Complete Code

Here's the complete code to get you started with Gitlab and Pydantic AI:

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Gitlab
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["gitlab"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    gitlab_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[gitlab_mcp],
        instructions=(
            "You are a Gitlab assistant. Use Gitlab tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Gitlab.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())

Conclusion

You've built a Pydantic AI agent that can interact with Gitlab through Composio's Tool Router. With this setup, your agent can perform real Gitlab actions through natural language. You can extend this further by:
  • Adding other toolkits like Gmail, HubSpot, or Salesforce
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Gitlab for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.
TOOLS

Supported Tools

Every Gitlab action and event your agent gets out of the box.

Add Spent Time

Adds spent time to a GitLab issue for time tracking purposes.

Approve Merge Request

Approves a merge request in a GitLab project.

Archive Project

Tool to archive a project.

Cancel Job

Cancel a GitLab CI/CD job within a specified project.

Cancel Pipeline

Tool to cancel a running pipeline in a GitLab project.

Create Commit

Creates a new commit with multiple file operations in a GitLab project.

Create Commit Comment

Posts a comment to a specific commit in a GitLab project repository.

Create Repository File

Creates a new file in a GitLab repository at the specified path with the given content.

Create GitLab Group

Tool to create a new group in GitLab.

Create Issue Note

Creates a new note (comment) on a project issue in GitLab.

Create Label

Creates a new label for a GitLab project with specified name, color, and optional attributes.

Create Merge Request

Creates a new merge request in a GitLab project to propose changes from a source branch into a target branch.

Create Merge Request Draft Note

Creates and saves an unpublished merge request draft note that is visible only to its author.

Create Milestone

Creates a new milestone in a GitLab project.

Create Pipeline

Tool to create a new pipeline for a specific branch or tag in a GitLab project.

Create Project

Tool to create a new project in GitLab.

Create Project Issue

Tool to create a new issue in a GitLab project.

Create Repository Branch

Tool to create a new branch in a project.

Create Project Webhook

Creates a new webhook (project hook) for a GitLab project to receive real-time event notifications.

Delete Group

Deletes a GitLab group by its ID or URL-encoded path.

Delete Issue Note

Deletes a note (comment) from an issue in a GitLab project.

Delete Label

Deletes a label from a GitLab project by its ID or title.

Delete Merge Request

Tool to permanently delete a merge request from a GitLab project.

Delete Milestone

Deletes a project milestone by its ID.

Delete Pipeline

Tool to delete a CI/CD pipeline by its ID within a specified project.

Delete Project

Tool to delete a GitLab project by its ID.

Delete Repository Branch

Tool to delete a branch from a GitLab project repository.

Delete Repository File

Deletes a file from a GitLab repository by creating a new commit.

Delete Webhook

Deletes a project webhook/hook permanently from a GitLab project, removing the integration and stopping all event notifications.

Download Project Avatar

Tool to download a project's avatar image.

Erase Job

Tool to erase the content of a specified job within a project.

Fork Project

Forks a GitLab project to a specified namespace or the current user's namespace.

Get Commit References

Tool to get all references (branches or tags) a commit is pushed to.

Get Commit Sequence

Tool to get the sequence number of a commit in a project by following parent links from the given commit.

Get Current User

Retrieves information about the currently authenticated user.

Get Repository File

Retrieves a single file from a GitLab repository at a specific ref (branch, tag, or commit).

Get Group Details

Tool to retrieve information about a specific group by its ID.

Get Group Member

Tool to retrieve details for a specific group member.

Get Groups

Get Groups

Get Issue

Retrieves a single issue from a GitLab project by its internal ID (iid).

Get Issue Note

Retrieves a single comment (note) from a GitLab issue by its ID.

Get Job Details

Tool to retrieve details of a single job by its ID within a specified project.

Get Job Trace

Retrieves the trace (log output) for a specific CI/CD job within a project.

Get Project Label

Retrieves a single project label by its ID or title.

Get Merge Request Approvals

Retrieves aggregate approval status for a GitLab merge request on any GitLab tier.

Get Merge Request Approval State

Retrieves rule-level approval satisfaction for a GitLab merge request.

Get Merge Request Notes

Tool to fetch comments on a merge request.

Get Milestone

Retrieves a single milestone by its ID for a specific project.

Get Project

Tool to get a single project by ID or URL-encoded path.

Get Project Languages

Tool to list programming languages used in a project with percentages.

Get Project Member

Tool to retrieve details for a specific project member.

Get Project Member All

Tool to retrieve details for a specific project member (including inherited and invited members).

Get Project Merge Request

Tool to fetch full details for a single merge request when the MR IID is known.

Get Merge Request Commits

Tool to get commits of a merge request.

Get Project Merge Requests

Tool to retrieve a list of merge requests for a specific project.

Get Projects

Tool to list all projects accessible to the authenticated user.

List Merge Request Diff Versions

Tool to list all diff versions of a merge request.

Get Raw File

Retrieves the raw contents of a file from a GitLab repository without Base64 encoding.

Get Repository Branch

Tool to retrieve information about a specific branch in a project.

Get Repository Branches

Retrieves a list of repository branches for a project.

Get Single Commit

Tool to get a specific commit identified by the commit hash or name of a branch or tag.

Get Single Pipeline

Tool to retrieve details of a single pipeline by its ID within a specified project.

Get Issue Time Stats

Retrieves time tracking statistics for a specific issue in a project.

Get User

Tool to retrieve information about a specific user by their ID.

Get User Preferences

Tool to get the current user's preferences.

Get Users

Tool to retrieve a list of users from GitLab.

Get Any User's Status by ID

Tool to get a user's status by ID.

Get User Status

Tool to get the current user's status.

Get User Support PIN

Tool to get details of the current user's Support PIN.

Get Webhook

Retrieves detailed information about a specific project webhook by its ID.

Import project members

Tool to import members from one project to another.

List All Group Members

Tool to list all members of a group including direct, inherited, and invited members.

List All Project Members

Tool to list all members of a project (direct, inherited, invited).

List Billable Group Members

Tool to list billable members of a top-level group (including its subgroups and projects).

List Commit Comments

Retrieves all comments associated with a specific commit in a GitLab project.

List Group Members

Tool to list direct members of a group.

List Group Projects

Tool to list projects within a GitLab group by group ID or full path.

List Issue Notes

Retrieves all notes (comments and activity) for a specific project issue in GitLab.

List Labels

Lists all labels for a project with optional filtering by name, archived status, and ancestor inclusion.

List Merge Request Diffs

List the files changed by a GitLab merge request, including patch content.

List Merge Request Discussions

Lists grouped discussion threads and their notes for a merge request.

List Merge Requests

Retrieves a list of merge requests from across all accessible projects based on scope and filters.

List Project Milestones

Lists all milestones for a specific project with optional filtering by state, title, or search terms.

List Pending Group Members

Tool to list pending members of a group and its subgroups and projects.

List Pipeline Jobs

Tool to retrieve a list of jobs for a specified pipeline within a project.

List Project Groups

Tool to list ancestor groups of a project.

List Project Invited Groups

Tool to list groups invited to a project.

List Project Issues

Tool to list issues for a project with filtering options (state, labels, search, assignee, author, etc.

List Project Pipelines

Tool to retrieve a list of pipelines for a specified project.

List Project Shareable Groups

Tool to list groups that can be shared with a project.

List Project Repository Tags

Tool to retrieve a list of repository tags for a specified project.

List Project Transfer Locations

Tool to list namespaces available for project transfer.

List project users

Tool to list users of a project.

List Repository Commits

Tool to get a list of repository commits in a project.

List Repository Tree

List files and directories in a GitLab project's repository tree.

List User Projects

Tool to list projects owned by a specific user.

List Webhooks

Tool to list all webhooks configured for a GitLab project.

Merge Merge Request

Merge a GitLab merge request immediately or enable auto-merge when checks pass.

Move Issue

Moves an issue from one project to another in GitLab.

Play Job

Triggers execution of a manual job in a GitLab project.

Create Support PIN

Tool to create a support PIN for your authenticated user.

Protect Branch

Protects a repository branch in a GitLab project by setting access controls for push, merge, and unprotect operations.

Update User Preferences

Tool to update the current user's preferences.

Reset Spent Time

Resets the total spent time for a specified GitLab issue to 0 seconds.

Reset Time Estimate

Resets the estimated time for a specified issue to 0 seconds.

Retry Pipeline

Retries failed or canceled jobs in a pipeline.

Set Time Estimate

Sets the estimated time to complete an issue in a GitLab project.

Set User Status

Tool to set the current user's status.

Share Project With Group

Tool to share a project with a group.

Star Project

Stars a project in GitLab, marking it as a favorite for the authenticated user.

Start Housekeeping Task

Tool to start the housekeeping task for a project.

Unapprove Merge Request

Removes the approval from the currently authenticated user for a specified merge request.

Unprotect Branch

Tool to remove protection from a branch in a GitLab project.

Unstar Project

Unstar a previously starred GitLab project to remove it from your favorites list.

Update GitLab Group

Updates an existing GitLab group's settings and properties.

Update Issue Note

Updates an existing note (comment) on a GitLab issue.

Update Label

Updates an existing label in a GitLab project by modifying its name, color, description, priority, or archived status.

Update Merge Request

Updates an existing merge request in a GitLab project (title, description, assignees, reviewers, labels, state, etc.

Update Milestone

Updates an existing milestone in a GitLab project, allowing you to modify the title, description, dates, or state.

Update Project Issue

Tool to update an existing issue in a GitLab project (title, description, labels, assignees, state, etc.

Update Repository File

Updates an existing file in a GitLab repository.

Update Webhook

Updates an existing project webhook configuration including URL, event triggers, SSL verification, and authentication token.

Validate Credential

Validates the authentication credentials by retrieving the currently authenticated user's information.

FAQ

Frequently asked questions

With a standalone Gitlab MCP server, the agents and LLMs can only access a fixed set of Gitlab tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Gitlab and many other apps based on the task at hand, all through a single MCP endpoint.

Yes, you can. Pydantic AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Gitlab tools.

Yes, absolutely. You can configure which Gitlab scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Gitlab data and credentials are handled as safely as possible.

Start with Gitlab.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Gitlab tool your agent needs.Free to start.

Start building