Official agent skill

Azure Service Bus for Python

by microsoft in microsoft/skills

Reference for the Azure Service Bus Python SDK: queues, topics and subscriptions, sending and receiving messages, receive modes and DefaultAzureCredential authentication.

OfficialMITAuto-check passedBackend & APIs

Install Azure Service Bus for Python

skills CLI
$ npx skills add microsoft/skills --skill azure-servicebus-py -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install microsoft/skills azure-servicebus-py --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.github/plugins/azure-sdk-python/skills/azure-servicebus-py .claude/skills/azure-servicebus-py && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
azure-servicebus-py
GitHub stars
3.1k
Token cost
~2.6k tokens
SKILL.md length
382 words
Files
4 (incl. scripts, references)
Skills in repo
150
Repo updated
First seen
Licence
MIT

At a glance

Reference for the Azure Service Bus Python SDK: queues, topics and subscriptions, sending and receiving messages, receive modes and DefaultAzureCredential authentication.

  • Works in 9 steps: Pick sync OR async and stay consistent.… → Always use context managers for clients… → Use DefaultAzureCredential for portable… → …
  • Sending or receiving Azure Service Bus messages from Python
  • SKILL.md covers Installation, Environment Variables, Authentication & Lifecycle and Client Types, plus 11 more sections
  • Runs Python scripts from its folder; calls pip; reaches learn.microsoft.com; needs AZURE_TOKEN_CREDENTIALS

What it does

The skill starts with installing `azure-servicebus` and `azure-identity` and the environment variables for the namespace, queue name and topic name. Two rules apply to every sample. Prefer `DefaultAzureCredential`, which works locally through the Azure CLI, VS Code or the Developer CLI and in Azure through managed or workload identity, and avoid connection strings and keys; in production set `AZURE_TOKEN_CREDENTIALS=prod` to limit the credential chain. And wrap every client in a context manager, sync or async, so transports and token caches are released.

Client types are `ServiceBusClient` for the connection, plus senders and receivers obtained from it for queues, topics and subscriptions. Examples cover async sending and receiving, and receive modes, where `PEEK_LOCK` is the default and requires completing or abandoning each message. Bundled references cover dead-letter handling and messaging patterns, and a setup script is included.

When your agent uses it

  • Sending or receiving Azure Service Bus messages from Python
  • Working with queues, topics and subscriptions in an enterprise messaging setup
  • Switching Service Bus code from connection strings to DefaultAzureCredential

Example prompts

  • “Write an async Python sender and receiver for an Azure Service Bus queue using DefaultAzureCredential.”
  • “Add a subscription receiver for our topic and handle messages with PEEK_LOCK.”
  • “Replace the connection string in this Service Bus client with managed identity.”

Requirements

  • Python with azure-servicebus and azure-identity installed
  • An Azure Service Bus namespace and credentials to reach it

Workflow steps

9 steps, taken from the first numbered list in SKILL.md.

  1. Pick sync OR async and stay consistent. Do not mix azure.xxx sync clients with azure.xxx.aio async clients in the same call path. Choose…
  2. Always use context managers for clients and async credentials. Wrap every client in with Client(...) as client: (sync) or async with…
  3. Use DefaultAzureCredential for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
  4. Use async client for production workloads
  5. Complete messages after successful processing
  6. Use dead-letter queue for poison messages
  7. Use sessions for ordered, FIFO processing
  8. Use message batches for high-throughput scenarios
  9. Set max_wait_time to avoid infinite blocking

What it can do on your machine

Read from SKILL.md and the folder at commit 354361d. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 1 file in scripts/ (Python), which the agent can run.

    Shell commands in SKILL.md call:

    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • learn.microsoft.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • AZURE_TOKEN_CREDENTIALS

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Azure Service Bus for Python loads about 2.6k tokens when it runs, and up to ~9.6k if it reads all its reference files. Until then it costs about 59 tokens; SKILL.md has 382 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~59
When it runs · the whole SKILL.md, loaded when a task matches
~2.6k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~9.6k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from microsoft/skills at commit 354361d, republished under its MIT licence (© microsoft). 382 words, ~2,588 tokens.

Download SKILL.mdSave it as .claude/skills/azure-servicebus-py/SKILL.md (or your agent's skills folder). This skill also uses 3 other files; get the full folder from GitHub.
name
azure-servicebus-py
description
Azure Service Bus SDK for Python messaging. Use for queues, topics, subscriptions, and enterprise messaging patterns. Triggers: "service bus", "ServiceBusClient", "queue", "topic", "subscription", "message broker".
license
MIT
metadata.author
Microsoft
metadata.version
1.0.0
metadata.package
azure-servicebus

Azure Service Bus SDK for Python

Enterprise messaging for reliable cloud communication with queues and pub/sub topics.

Installation

bash
pip install azure-servicebus azure-identity

Environment Variables

bash
SERVICEBUS_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net  # Required for all auth methods
SERVICEBUS_QUEUE_NAME=myqueue  # Required for queue operations
SERVICEBUS_TOPIC_NAME=mytopic  # Required for topic operations
SERVICEBUS_SUBSCRIPTION_NAME=mysubscription  # Required for subscription operations
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production

Authentication & Lifecycle

🔑 Two rules apply to every code sample below:

  1. Prefer DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
    • Local dev: DefaultAzureCredential works as-is.
    • Production: set AZURE_TOKEN_CREDENTIALS=prod (or AZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.
  2. Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
    • Sync: with <Client>(...) as client:
    • Async: async with <Client>(...) as client: and async with DefaultAzureCredential() as credential: (from azure.identity.aio)

Snippets may abbreviate this setup, but production code should always follow both rules.

python
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.servicebus import ServiceBusClient

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
namespace = "<namespace>.servicebus.windows.net"

with ServiceBusClient(
    fully_qualified_namespace=namespace,
    credential=credential
) as client:
    # Use client here (see following sections for operations)
    ...

Client Types

ClientPurposeGet From
ServiceBusClientConnection managementDirect instantiation
ServiceBusSenderSend messagesclient.get_queue_sender() / get_topic_sender()
ServiceBusReceiverReceive messagesclient.get_queue_receiver() / get_subscription_receiver()

Send Messages (Async)

python
import asyncio
from azure.servicebus.aio import ServiceBusClient
from azure.servicebus import ServiceBusMessage
from azure.identity.aio import DefaultAzureCredential

async def send_messages():
    credential = DefaultAzureCredential()
    
    async with ServiceBusClient(
        fully_qualified_namespace="<namespace>.servicebus.windows.net",
        credential=credential
    ) as client:
        sender = client.get_queue_sender(queue_name="myqueue")
        
        async with sender:
            # Single message
            message = ServiceBusMessage("Hello, Service Bus!")
            await sender.send_messages(message)
            
            # Batch of messages
            messages = [ServiceBusMessage(f"Message {i}") for i in range(10)]
            await sender.send_messages(messages)
            
            # Message batch (for size control)
            batch = await sender.create_message_batch()
            for i in range(100):
                try:
                    batch.add_message(ServiceBusMessage(f"Batch message {i}"))
                except ValueError:  # Batch full
                    await sender.send_messages(batch)
                    batch = await sender.create_message_batch()
                    batch.add_message(ServiceBusMessage(f"Batch message {i}"))
            await sender.send_messages(batch)

asyncio.run(send_messages())

Receive Messages (Async)

python
async def receive_messages():
    credential = DefaultAzureCredential()
    
    async with ServiceBusClient(
        fully_qualified_namespace="<namespace>.servicebus.windows.net",
        credential=credential
    ) as client:
        receiver = client.get_queue_receiver(queue_name="myqueue")
        
        async with receiver:
            # Receive batch
            messages = await receiver.receive_messages(
                max_message_count=10,
                max_wait_time=5  # seconds
            )
            
            for msg in messages:
                print(f"Received: {str(msg)}")
                await receiver.complete_message(msg)  # Remove from queue

asyncio.run(receive_messages())

Receive Modes

ModeBehaviorUse Case
PEEK_LOCK (default)Message locked, must complete/abandonReliable processing
RECEIVE_AND_DELETERemoved immediately on receiveAt-most-once delivery
python
from azure.servicebus import ServiceBusReceiveMode

receiver = client.get_queue_receiver(
    queue_name="myqueue",
    receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE
)

Message Settlement

python
async with receiver:
    messages = await receiver.receive_messages(max_message_count=1)
    
    for msg in messages:
        try:
            # Process message...
            await receiver.complete_message(msg)  # Success - remove from queue
        except ProcessingError:
            await receiver.abandon_message(msg)  # Retry later
        except PermanentError:
            await receiver.dead_letter_message(
                msg,
                reason="ProcessingFailed",
                error_description="Could not process"
            )
ActionEffect
complete_message()Remove from queue (success)
abandon_message()Release lock, retry immediately
dead_letter_message()Move to dead-letter queue
defer_message()Set aside, receive by sequence number

Topics and Subscriptions

python
# Send to topic
sender = client.get_topic_sender(topic_name="mytopic")
async with sender:
    await sender.send_messages(ServiceBusMessage("Topic message"))

# Receive from subscription
receiver = client.get_subscription_receiver(
    topic_name="mytopic",
    subscription_name="mysubscription"
)
async with receiver:
    messages = await receiver.receive_messages(max_message_count=10)

Sessions (FIFO)

python
# Send with session
message = ServiceBusMessage("Session message")
message.session_id = "order-123"
await sender.send_messages(message)

# Receive from specific session
receiver = client.get_queue_receiver(
    queue_name="session-queue",
    session_id="order-123"
)

# Receive from next available session
from azure.servicebus import NEXT_AVAILABLE_SESSION
receiver = client.get_queue_receiver(
    queue_name="session-queue",
    session_id=NEXT_AVAILABLE_SESSION
)

Scheduled Messages

python
from datetime import datetime, timedelta, timezone

message = ServiceBusMessage("Scheduled message")
scheduled_time = datetime.now(timezone.utc) + timedelta(minutes=10)

# Schedule message
sequence_number = await sender.schedule_messages(message, scheduled_time)

# Cancel scheduled message
await sender.cancel_scheduled_messages(sequence_number)

Dead-Letter Queue

python
from azure.servicebus import ServiceBusSubQueue

# Receive from dead-letter queue
dlq_receiver = client.get_queue_receiver(
    queue_name="myqueue",
    sub_queue=ServiceBusSubQueue.DEAD_LETTER
)

async with dlq_receiver:
    messages = await dlq_receiver.receive_messages(max_message_count=10)
    for msg in messages:
        print(f"Dead-lettered: {msg.dead_letter_reason}")
        await dlq_receiver.complete_message(msg)

Sync Client (for simple scripts)

python
from azure.servicebus import ServiceBusClient, ServiceBusMessage
from azure.identity import DefaultAzureCredential

with ServiceBusClient(
    fully_qualified_namespace="<namespace>.servicebus.windows.net",
    credential=DefaultAzureCredential()
) as client:
    with client.get_queue_sender("myqueue") as sender:
        sender.send_messages(ServiceBusMessage("Sync message"))
    
    with client.get_queue_receiver("myqueue") as receiver:
        for msg in receiver:
            print(str(msg))
            receiver.complete_message(msg)
Show full SKILL.md (162 more words)Show less

Best Practices

  1. Pick sync OR async and stay consistent. Do not mix azure.xxx sync clients with azure.xxx.aio async clients in the same call path. Choose one mode per module.
  2. Always use context managers for clients and async credentials. Wrap every client in with Client(...) as client: (sync) or async with Client(...) as client: (async) for proper cleanup. For async DefaultAzureCredential from azure.identity.aio, also use async with credential: so tokens and transports are cleaned up.
  3. Use DefaultAzureCredential for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
  4. Use async client for production workloads
  5. Complete messages after successful processing
  6. Use dead-letter queue for poison messages
  7. Use sessions for ordered, FIFO processing
  8. Use message batches for high-throughput scenarios
  9. Set max_wait_time to avoid infinite blocking

Reference Files

FileContents
references/patterns.mdCompeting consumers, sessions, retry patterns, request-response, transactions
references/dead-letter.mdDLQ handling, poison messages, reprocessing strategies
scripts/setup_servicebus.pyCLI for queue/topic/subscription management and DLQ monitoring

© microsoft, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 3 other files (scripts, references) in .github/plugins/azure-sdk-python/skills/azure-servicebus-py of microsoft/skills.

  • SKILL.md
  • references/dead-letter.md
  • references/patterns.md
  • scripts/setup_servicebus.py

Open the folder on GitHubat commit 354361d

Compare with similar skills

Azure Service Bus for Python next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Azure Service Bus for Python compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Azure Service Bus for Python this skillmicrosoft/skills3.1k—~2.6kAutomated safety check: PassMIT
Integration Test GeneratorArabelaTso/Skills-4-SE253—~2.1kAutomated safety check: PassApache-2.0
Azure Event HubsMicrosoftDocs/Agent-Skills777—~3.8kAutomated safety check: PassCC-BY-4.0
Azure Preparemicrosoft/GitHub-Copilot-for-Azure2551 repos~3.2kAutomated safety check: PassMIT
AWS Serverless Edazxkane/aws-skills3674 repos~3.2kAutomated safety check: PassMIT
Windmill Trigger Type Checklistwindmill-labs/windmill18k—~4.7kAutomated safety check: PassCustom licence

Similar skills

  • Integration Test Generator

    ArabelaTso/Skills-4-SE

    Generate integration tests for multiple interacting components in Python.

    253 GitHub stars~2.1k tokensUpdated 1 mo ago
    Testing & QAAuto-check passed
  • Azure Event Hubs

    MicrosoftDocs/Agent-Skills

    Official

    Expert knowledge for Azure Event Hubs development including troubleshooting, best practices, decision making, architecture & design patterns, limits & quotas, security, configuration, integrations &…

    777 GitHub stars~3.8k tokensUpdated 2 days ago
    DevelopmentAuto-check passed
  • Azure Prepare

    microsoft/GitHub-Copilot-for-Azure

    Official

    Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow.

    255 GitHub starsUsed in 1 repo~3.2k tokens
    DevOps & CloudAuto-check passed
  • AWS Serverless Eda

    zxkane/aws-skills

    AWS serverless and event-driven architecture expert based on Well-Architected Framework.

    367 GitHub starsUsed in 4 repos~3.2k tokens
    Backend & APIsAuto-check passed
  • Windmill Trigger Type Checklist

    windmill-labs/windmill

    Checklist of every backend, frontend, CLI and capture change needed to add a new TriggerCrud-based trigger type, such as Azure, GCP or Kafka, to Windmill.

    18k GitHub stars~4.7k tokensUpdated today
    Backend & APIsAuto-check passed
  • Foundatio

    FoundatioFx/Foundatio

    A skill your agent uses when working with Foundatio infrastructure abstractions for .NET -- caching, queuing, messaging, file storage, distributed locking, or background jobs.

    2.1k GitHub stars~3.9k tokensUpdated today
    Backend & APIsAuto-check passed

More from microsoft/skills

All 150 skills in this repo
  • Official

    Reference for building on Microsoft Foundry with the azure-ai-projects Python SDK: project clients, versioned agents, evaluations, connections, datasets and indexes.

    3.1k GitHub starsUsed in 6 repos~2.8k tokens
    Auto-check passed
  • Official

    Python guidance for the Azure AI Search SDK covering vector, hybrid and semantic search, index management and indexers, with Entra ID authentication preferred over keys.

    3.1k GitHub starsUsed in 6 repos~4.4k tokens
    Auto-check passed
  • Official

    Covers producer, consumer, and checkpoint-store setup for Azure Event Hubs streaming in Python, with Entra ID auth and partition targeting.

    3.1k GitHub starsUsed in 1 repo~2.3k tokens
    Auto-check passed
  • Pydantic Models Py

    microsoft/skills

    Official

    Create Pydantic models following the multi-model pattern with Base, Create, Update, Response, and InDB variants.

    3.1k GitHub starsUsed in 6 repos~496 tokens
    Auto-check passed
  • DebugView CLI

    microsoft/skills

    Official

    Captures and filters Windows user-mode and kernel debug output from the command line with the Sysinternals DebugView CLI, including bounded runs suited to agents.

    3.1k GitHub starsUsed in 1 repo~2.7k tokens
    Auto-check passed
  • Frontend UI Dark TS

    microsoft/skills

    Official

    Build dark-themed React applications using Tailwind CSS with custom theming, glassmorphism effects, and Framer Motion animations.

    3.1k GitHub starsUsed in 5 repos~3.6k tokens
    Auto-check passed

Categories

Questions about Azure Service Bus for Python

What does Azure Service Bus for Python do?

Reference for the Azure Service Bus Python SDK: queues, topics and subscriptions, sending and receiving messages, receive modes and DefaultAzureCredential authentication. The skill starts with installing `azure-servicebus` and `azure-identity` and the environment variables for the namespace, queue name and topic name. Two rules apply to every sample.

When should I use Azure Service Bus for Python?

Azure Service Bus for Python fits situations like: sending or receiving Azure Service Bus messages from Python; working with queues, topics and subscriptions in an enterprise messaging setup; switching Service Bus code from connection strings to DefaultAzureCredential.

How do I install Azure Service Bus for Python in Claude Code?

Run `npx skills add microsoft/skills --skill azure-servicebus-py -a claude-code`. Or copy the skill folder (.github/plugins/azure-sdk-python/skills/azure-servicebus-py in microsoft/skills) into .claude/skills/azure-servicebus-py in your project. Claude Code loads it when a task matches its description.

How do I install Azure Service Bus for Python in Codex?

Run `npx skills add microsoft/skills --skill azure-servicebus-py -a codex`. Or copy the skill folder (.github/plugins/azure-sdk-python/skills/azure-servicebus-py in microsoft/skills) into .agents/skills/azure-servicebus-py in your project. Codex loads it when a task matches its description.

Can I use Azure Service Bus for Python in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add microsoft/skills --skill azure-servicebus-py -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/azure-servicebus-py, .gemini/skills/azure-servicebus-py, .github/skills/azure-servicebus-py and .opencode/skills/azure-servicebus-py in your project.

What does Azure Service Bus for Python need to run?

Going by SKILL.md and its folder, Azure Service Bus for Python needs Python for the scripts in its folder, the command-line tools its instructions call (pip) and credentials named AZURE_TOKEN_CREDENTIALS. Our summary lists: Python with azure-servicebus and azure-identity installed; An Azure Service Bus namespace and credentials to reach it.

Does Azure Service Bus for Python access the network?

SKILL.md names 1 domain. In commands or code: learn.microsoft.com; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Azure Service Bus for Python safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Azure Service Bus for Python use?

Azure Service Bus for Python is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Azure Service Bus for Python use?

About 2.6k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 7k tokens, read only when the agent opens those files.

What are the alternatives to Azure Service Bus for Python?

Skills that share tags, products or a category with Azure Service Bus for Python: Integration Test Generator (ArabelaTso/Skills-4-SE, 253 stars), Azure Event Hubs (MicrosoftDocs/Agent-Skills, 777 stars), Azure Prepare (microsoft/GitHub-Copilot-for-Azure, 255 stars) and AWS Serverless Eda (zxkane/aws-skills, 367 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Azure Service Bus for Python?

microsoft (a GitHub organization, an official publisher) maintains it in microsoft/skills, which has 3,091 GitHub stars. The repository holds 150 skills in this directory. The repository was last updated on October 6, 2026.

Source: microsoft/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.