On this page

Available MCP Tools

The PubNub Model Context Protocol (MCP) Server provides three types of primitives that AI assistants can use:

  • Tools, which are functions that perform actions or retrieve data
  • Resources, which are data sources that can be read by the AI assistant
  • Prompts, which are pre-built prompt templates for common use cases

Authentication depends on how you run the server. The hosted server uses OAuth — authentication is handled automatically when you authorize your IDE. The locally installed server uses your PubNub API key via the PUBNUB_API_KEY environment variable. For setup instructions, refer to PubNub MCP Server.

Tools

The MCP server exposes 16 tools organized into five categories.

Documentation access

These tools retrieve SDK documentation to help you understand and implement PubNub features.

get_sdk_documentation

Retrieves SDK documentation for a specific programming language and feature.

* required
ParameterDescription
language *
Type: String
Default:
n/a
Programming language to retrieve documentation for.

Supported languages: asyncio, c-core, c-sharp, dart, freertos, go, java, javascript, kotlin, mbed, objective-c, php, posix-c, posix-cpp, python, ruby, rust, swift, unity, unreal, windows-c, windows-cpp.
feature *
Type: String
Default:
n/a
SDK feature to retrieve documentation for.

Supported features: access-manager, channel-groups, configuration, encryption, files, message-actions, misc, mobile-push, presence, publish, storage-and-playback, subscribe. App Context features (where supported by the language): appcontext-channel, appcontext-members, appcontext-memberships, appcontext-user.
Supported features

Not all features are available for all languages. The tool returns an error if you request an unsupported combination.

Sample prompt
Get the JS SDK docs for publish and subscribe.

get_chat_sdk_documentation

Retrieves Chat SDK documentation for a specific programming language and feature.

* required
ParameterDescription
language *
Type: String
Default:
n/a
Chat SDK language to retrieve documentation for.

Supported languages: javascript, kotlin, swift, unity, unreal.
feature *
Type: String
Default:
n/a
Chat SDK feature to retrieve documentation for.

Supported features: channels-create, channels-delete, channels-details, channels-invite, channels-join, channels-leave, channels-list, channels-membership, channels-typing-indicator, channels-updates, messages-delete, messages-details, messages-drafts, messages-files, messages-forward, messages-history, messages-reactions, messages-read-receipts, messages-send-receive, messages-threads, messages-unread, users-create, users-delete, users-details, users-list, users-mentions, users-presence, users-updates, and more.
Sample prompt
Get the Swift Chat SDK docs for sending and receiving messages.

how_to

Retrieves PubNub conceptual guides with detailed instructions for implementing specific features and use cases.

* required
ParameterDescription
slug *
Type: String
Default:
n/a
Guide identifier.

Available guides include topics like Unity/Unreal game development, Chat SDK features, Admin Portal configuration, IoT solutions, presence, push notifications, moderation, and more.
When to use

Use this tool for overviews, integration instructions, best practices, and troubleshooting tips. For detailed API reference and SDK code samples, also use get_sdk_documentation or get_chat_sdk_documentation.

Sample prompt
Show me how to add real-time chat to my Unity game.

write_pubnub_app

Retrieves the comprehensive PubNub best practices guide covering architecture, security, channel modeling, and optimization.

The guide covers:

Sample prompt
What are the best practices for building PubNub applications?

get_sdk_migration_guide

Retrieves SDK migration guides for upgrading between PubNub SDK versions.

* required
ParameterDescription
language *
Type: String
Default:
n/a
Programming language to retrieve the migration guide for.

Supported languages: go, java, javascript, kotlin, php, unity.
version *
Type: String
Default:
n/a
Target SDK version to migrate to.

Available versions per language: go (8), java (10, 13), javascript (8), kotlin (10, 13), php (8), unity (7).

:::note Supported combinations Not all versions are available for all languages. The tool returns an error if you request an unsupported combination. :::

Sample prompt
How do I migrate my JavaScript PubNub SDK to v8?

get_general_migration_guide

Retrieves migration guides for cross-cutting PubNub platform changes such as encryption upgrades, push notification migrations, and API version transitions.

* required
ParameterDescription
slug *
Type: String
Default:
n/a
Migration guide identifier.

Available guides: 256-bit-encryption-migration, apns2-migration-guide, legacy-fcm-migration-guide, legacy-webhooks-migration-guide, objects-v2-migration, pam-v3-migration, react-components-chat-sdk.

:::tip When to use Use this tool for platform-wide changes that affect multiple SDKs or services, such as migrating to 256-bit encryption, upgrading from legacy APNs or FCM push notification setups, moving to Access Manager v3, or replacing deprecated webhooks. For SDK-specific version upgrades, use get_sdk_migration_guide instead. :::

Sample prompt
How do I migrate to 256-bit encryption?

App & Keyset management

These tools manage your PubNub applications and keysets.

manage_apps

Manages PubNub apps with operations: list, create, and update.

Admin API access required

This tool requires Admin Portal API access. When using the locally installed server, it requires PUBNUB_API_KEY authentication — not available with email/password authentication.

* required
ParameterDescription
operation *
Type: String
Default:
n/a
Operation to perform: list, create, or update.
data
Type: Object
Default:
n/a
Operation-specific data. Required for create and update operations.
Data object by operation
  • list: No data required.

  • create

    FieldTypeRequiredDescription
    name
    String
    Yes
    Name of the app to create.
  • update

    FieldTypeRequiredDescription
    id
    String
    Yes
    App ID to update.
    name
    String
    Yes
    New name for the app.
Sample prompts
List all my PubNub apps.
Create a new PubNub app called MyRealtimeApp.
Rename app 12345 to ProductionApp.

manage_keysets

Manages PubNub keysets with operations: get, list, create, and update. New keysets are created with Message Persistence, App Context, Files, and Presence enabled by default.

Admin API access required

This tool requires Admin Portal API access. When using the locally installed server, it requires PUBNUB_API_KEY authentication — not available with email/password authentication.

* required
ParameterDescription
operation *
Type: String
Default:
n/a
Operation to perform: get, list, create, or update.
data
Type: Object
Default:
n/a
Operation-specific data. Required for get, create, and update. Optional for list.
Data object by operation
  • get
FieldTypeRequiredDescription
id
String
Yes
Keyset ID to retrieve.
  • list
FieldTypeRequiredDescription
appId
String
No
App ID to list keysets for. If not provided, lists keysets for the entire account.
  • create
FieldTypeRequiredDescription
name
String
Yes
Name of the keyset.
appId
String
No
App ID to create keyset in. If not provided, a new app is created.
type
String
Yes
Keyset type: testing for testing/development or production for live environments.
config
Object
Yes
Keyset feature configuration. Refer to the Config object section below.
  • update
FieldTypeRequiredDescription
id
String
Yes
Keyset ID to update.
config
Object
Yes
Config to update. Same structure as for create.
Config object

The config object contains four optional sub-objects for configuring keyset features:

FieldTypeRequiredDescription
enabled
Boolean
Yes
Enable or disable message persistence.
retention
Number
Conditional
Days to retain messages (1, 7, 30, 90, 180, 365, or 0 for unlimited). Required when enabled=true.
includePresenceEvents
Boolean
No
Store presence event messages in history.
deleteFromHistory
Boolean
No
Allow API calls to delete specific messages from history.
FieldTypeRequiredDescription
enabled
Boolean
Yes
Enable or disable App Context (Objects).
region
String
Conditional
Storage region. Required when enabled=true. Cannot be changed once set.

Values: aws-iad-1, aws-pdx-1, aws-fra-1, aws-bom-1, aws-hnd-1.
userMetadataEvents
Boolean
No
Trigger events when user metadata changes.
channelMetadataEvents
Boolean
No
Trigger events when channel metadata changes.
membershipEvents
Boolean
No
Trigger events when memberships are added, updated, or removed.
disallowGetAllChannelMetadata
Boolean
No
Disallow the "Get All Channel Metadata" call.
disallowGetAllUserMetadata
Boolean
No
Disallow the "Get All User Metadata" call.
referentialIntegrity
Boolean
No
Require user/channel to exist before creating memberships.
FieldTypeRequiredDescription
enabled
Boolean
Yes
Enable or disable file sharing.
region
String
Conditional
Storage region. Required when enabled=true. Cannot be changed once set.

Values: us-east-1, us-west-1, eu-central-1, ap-south-1, ap-northeast-1.
retention
Number
Conditional
Days to retain files (1, 7, 30, or 0 for unlimited). Required when enabled=true.
FieldTypeRequiredDescription
enabled
Boolean
Yes
Enable or disable presence.
announceMax
Number
No
Max occupants before switching to occupancy counts (0-100).
interval
Number
No
Seconds between occupancy announcements (min 10).
deltas
Boolean
No
Include joined/left UUIDs in interval events.
generateLeaveOnDisconnect
Boolean
No
Trigger leave events on connection close.
streamFiltering
Boolean
No
Filter presence events at client level.
activeNoticeChannel
String
No
Channel for active/inactive notifications.
debounce
Number
No
Seconds to wait before allowing joins after leaves.
Immutable settings

The region settings in appContext and files cannot be changed after the keyset is created. Always confirm these values with the user before creating a keyset.

Sample prompts
Get details for keyset abc123.
List all keysets for app 12345.
Create a production keyset with Message Persistence (30 days retention), Presence, and App Context in US East.
Enable Presence with interval events on keyset 67890.

get_usage_metrics

Fetches usage metrics from the PubNub Admin API for an account, app, or keyset.

Admin API access required

This tool requires Admin Portal API access. When using the locally installed server, it requires PUBNUB_API_KEY authentication — not available with email/password authentication.

* required
ParameterDescription
entityType *
Type: String
Default:
n/a
Entity type to fetch metrics for: account, app, or keyset.
entityId *
Type: String
Default:
n/a
The ID of the entity (account ID, app ID, or keyset ID).
from *
Type: String
Default:
n/a
Start date (inclusive) in YYYY-MM-DD format.
to *
Type: String
Default:
n/a
End date (exclusive) in YYYY-MM-DD format.
metrics *
Type: Array
Default:
n/a
Array of metric names to retrieve. At least one metric must be specified.
Available metrics

The metrics array accepts values from the following categories:

CategoryMetrics
Core transactions
txn_total, mtd_txn_total, replicated, signals, edge
MAU/UUID
mtd_uuid, uuid, pn_uuid
Messages
msgs_total, publish, subscribe_msgs, history_msgs, files_msgs, push_msgs
Storage
bytes_stored, bytes_stored_messages, bytes_stored_files, bytes_stored_users, bytes_stored_memberships, bytes_stored_blocks, bytes_stored_channel_groups, bytes_stored_push, bytes_stored_size_auth
Access Manager
accessmanager_grants_transactions, accessmanager_grants_v3_transactions, accessmanager_audits_transactions, accessmanager_replicated, accessmanager_edge, accessmanager_clienterrors_transactions
Functions
executions, kv_read_transactions, kv_write_transactions, xhr_transactions, functions_replicated, functions_edge, fire_transactions, fire_eh_transactions, fire_client_transactions, misfire_client_transactions, misfire_eh_transactions
History
history_transactions, history_with_actions_transactions, history_messages_count_transactions, history_edge, history_clienterrors_transactions, history_with_actions_clienterrors_transactions, history_with_actions_unauthorized_transactions
Message Actions
message_actions, message_actions_add_transactions, message_actions_get_transactions, message_actions_remove_transactions, subscribe_message_actions_transactions, message_actions_clienterrors_transactions, message_actions_unauthorized_transactions
Objects/App Context
objects_create_user_transactions, objects_get_user_transactions, objects_update_user_transactions, objects_delete_user_transactions, objects_get_all_users_transactions, objects_create_space_transactions, objects_get_space_transactions, objects_update_space_transactions, objects_delete_space_transactions, objects_get_all_spaces_transactions, objects_get_user_space_memberships_transactions, objects_get_space_user_memberships_transactions, objects_update_user_space_memberships_transactions, objects_update_space_user_memberships_transactions, objects_users, objects_spaces, objects_memberships, objects_replicated, objects_edge, objects_errors, objects_clienterrors_transactions, objects_unauthorized_transactions, internal_publish_objects_transactions
Presence
presence_herenow_transactions, presence_herenow_global_transactions, presence_wherenow_transactions, presence_getuserstate_transactions, presence_setuserstate_transactions, presence_leave_transactions, presence_heartbeats_transactions, presence_replicated, presence_edge, presence_clienterrors_transactions
Push Notifications
apns_sent_transactions, apns_removed_transactions, gcm_sent_transactions, gcm_removed_transactions, mpns_sent_transactions, mpns_removed_transactions, push_device_writes_transactions, push_device_reads_transactions, push_notifications_replicated, push_notifications_edge, push_notifications_apple, push_notifications_android, push_notifications_microsoft, push_device_clienterrors_transactions
Subscribe
subscribe_transactions, subscribe_heartbeats_transactions, subscribe_timeouts_transactions, subscribe_objects_transactions, subscribe_streaming_transactions, subscribe_signal_transactions, subscribe_files_transactions, subscribe_bytes, subscribe_edge, subscribe_clientclosedconnection_transactions, subscribe_clienterrors_transactions, subscribe_unauthorized_transactions
Publish
publish_transactions, publish_bytes, publish_msg_average_size, publish_replicated, publish_edge, publish_clienterrors_transactions, publish_unauthorized_transactions
Signal
signal_transactions, signal_clienterrors_transactions, signal_unauthorized_transactions
Files
files_publish_transactions, files_get_file_transactions, files_get_all_files_transactions, files_delete_file_transactions, files_generate_url_transactions, files_replicated, files_edge, files_clienterrors_transactions, files_unauthorized_transactions
Stream Controller
streamcontroller_reads_transactions, streamcontroller_writes_transactions, streamcontroller_clienterrors_transactions, steam_controller_edge, steam_controller_replicated
Other
free, events_ingested, message_ratio, mtd_txn_mtd_uuid_ratio, channel, ip, key_ip_ch, key_ip_ua, pres_pub
Sample prompts
Get the total transactions for my account from January 1st to January 31st.
Show me the MAU metrics for app 12345 for the last month.
Fetch publish and subscribe transaction counts for keyset abc123 from 2024-01-01 to 2024-01-07.

Real-time communication

These tools interact with PubNub's real-time messaging infrastructure for publishing, subscribing, and managing presence and App Context data.

Optional keys with fixed mode (local server)

When using the locally installed server with PUBNUB_PUBLISH_KEY and PUBNUB_SUBSCRIBE_KEY environment variables configured, the publishKey and subscribeKey parameters are not required for these tools. The server automatically uses the configured keys. Refer to PubNub keys configuration for details.

send_pubnub_message

Sends a message or signal to a PubNub channel. Returns a publish timetoken confirming successful delivery.

* required
ParameterDescription
channel *
Type: String
Default:
n/a
Channel to publish to.
message *
Type: String or Object
Default:
n/a
Message payload (string or JSON object).
type
Type: String
Default:
message
Type of message: message (regular) or signal (lightweight).
publishKey *
Type: String
Default:
n/a
Publish key from your keyset.
subscribeKey *
Type: String
Default:
n/a
Subscribe key from your keyset.
Signals

Signals are limited to 64 bytes and are not stored in message history. Use them for lightweight, ephemeral data like typing indicators.

Sample prompt
Send "Hello, World!" to the chat-room channel.

subscribe_and_receive_pubnub_messages

Subscribes to a channel and waits for messages. Returns an array of received messages with their content and metadata.

* required
ParameterDescription
channel *
Type: String
Default:
n/a
Channel to subscribe to.
messageCount
Type: Number
Default:
1
Number of messages to wait for before returning.
timeout
Type: Number
Default:
10
Maximum wait time in seconds. Maximum value is 30.
publishKey *
Type: String
Default:
n/a
Publish key from your keyset.
subscribeKey *
Type: String
Default:
n/a
Subscribe key from your keyset.
Sample prompt
Subscribe to the notifications channel and wait for 3 messages.

get_pubnub_messages

Retrieves historical messages from channels using Message Persistence. Returns historical messages with content, timetokens, and metadata.

* required
ParameterDescription
channels *
Type: Array
Default:
n/a
List of channel names to fetch history from.
start
Type: String
Default:
n/a
Start timetoken (exclusive) for pagination.
end
Type: String
Default:
n/a
End timetoken (inclusive) for pagination.
count
Type: Number
Default:
100
Number of messages to return per channel.
publishKey *
Type: String
Default:
n/a
Publish key from your keyset.
subscribeKey *
Type: String
Default:
n/a
Subscribe key from your keyset.
Sample prompt
Get the last 50 messages from the chat-room channel.

get_pubnub_presence

Retrieves real-time Presence information. Returns presence data including occupancy counts and user UUIDs.

* required
ParameterDescription
channels
Type: Array
Default:
[]
Channels to query presence for (HereNow).
channelGroups
Type: Array
Default:
[]
Channel groups to query presence for.
uuid
Type: String
Default:
n/a
UUID to query channel subscriptions for (WhereNow).
publishKey *
Type: String
Default:
n/a
Publish key from your keyset.
subscribeKey *
Type: String
Default:
n/a
Subscribe key from your keyset.
Sample prompt
How many users are in the lobby channel?

manage_app_context

Performs CRUD operations on App Context objects.

* required
ParameterDescription
type *
Type: String
Default:
n/a
Object type: user, channel, or membership.
operation *
Type: String
Default:
n/a
Operation: get, set, remove, or getAll.
id *
Type: String
Default:
n/a
Identifier: UUID for user and membership operations, channel ID (for example, team.red) for channel metadata and channel member operations.
publishKey *
Type: String
Default:
n/a
Publish key from your keyset.
subscribeKey *
Type: String
Default:
n/a
Subscribe key from your keyset.
data
Type: Object
Default:
n/a
Data for set/remove operations. Refer to the data object tables for more details.
options
Type: Object
Default:
n/a
Additional options like filters, pagination, and includes.
User data object (for type: "user")

For details, refer to User metadata.

FieldTypeDescription
name
String
User's display name.
email
String
User's email address.
externalId
String
External system identifier.
profileUrl
String
URL to profile picture.
type
String
User type.
status
String
User status.
custom
Object
Custom key-value pairs (scalar values only).
Channel data object (for type: "channel")

For details, refer to Channel metadata.

FieldTypeDescription
name
String
Channel display name.
description
String
Channel description.
type
String
Channel type.
status
String
Channel status.
custom
Object
Custom key-value pairs (scalar values only).
Membership data object (for type: "membership")

For details, refer to Membership metadata.

For setting memberships, provide:

{
"channels": ["channel-1", "channel-2"]
}

Or with custom data:

{
"channels": [
{ "id": "channel-1", "custom": { "role": "admin" } }
]
}
Sample prompts
Create a user profile for UUID user-123 with name John Doe.
Add user-123 to the general-chat channel.
List all members of the team-red channel.

Illuminate analytics and automation

These tools integrate with Illuminate to build real-time analytics pipelines and event-driven automations on top of PubNub message data.

manage_illuminate

Manages Illuminate resources including Business Objects, metrics, queries, Decisions, and Dashboards.

Admin API access required

This tool requires Admin Portal API access. When using the locally installed server, it requires PUBNUB_API_KEY authentication — not available with email/password authentication.

* required
ParameterDescription
operation *
Type: String
Default:
n/a
Operation to perform. Refer to the Supported operations table below.
resource
Type: String
Default:
n/a
Illuminate resource type: business-object, metric, query, decision, or dashboard. Required for most operations.
id
Type: String
Default:
n/a
Resource UUID. Required for get, update, delete, activate, deactivate, and get-fields.
data
Type: Object
Default:
n/a
Request body for create, update, and execute-adhoc operations.
bo_id
Type: String
Default:
n/a
Business Object UUID. Required for publish-fake-data, raw-snapshot, aggregate, and field-health.
query_id
Type: String
Default:
n/a
Saved query UUID. Required for verify-query.
decision_id
Type: String
Default:
n/a
Decision UUID. Required for check-action-log.
subscribe_key
Type: String
Default:
n/a
PubNub subscribe key (sub-c-...). Required for business-object activate and publish-fake-data. Obtain via manage_keysets.
publish_key
Type: String
Default:
n/a
PubNub publish key (pub-c-...). Required for publish-fake-data. Obtain via manage_keysets.
secret_key
Type: String
Default:
n/a
PubNub secret key (sec-c-...). Use with publish-fake-data when Access Manager is enabled on the keyset.
auth_key
Type: String
Default:
n/a
Access Manager v3 grant token. Alternative to secret_key for publish-fake-data when Access Manager is enabled.
scenario
Type: String
Default:
generic
Fake-data scenario for publish-fake-data: generic, chat-flooding, or cross-posting.
count
Type: Number
Default:
5
Number of fake messages to publish (1–50). Used with publish-fake-data.
channel
Type: String
Default:
test-channel
Target channel for publish-fake-data.
limit
Type: Number
Default:
50
Maximum rows to return for raw-snapshot, aggregate, and field-health (1–500).
group_by
Type: Array
Default:
n/a
Field aliases to group by for aggregate. Defaults to the first two TEXT fields in the Business Object.
pipeline
Type: Object
Default:
n/a
Full pipeline body for custom-query. Must include version: "2.0".
Supported resources
ResourceDescription
business-object
Data schema that maps JSONPath fields from PubNub messages to Illuminate dimensions.
metric
Aggregation (COUNT, SUM, AVG, MIN, MAX) computed over a Business Object field.
query
Flexible data pipeline with sources, optional transforms, and output.
decision
Automation rule that evaluates conditions against metrics or query results and fires actions.
dashboard
Visualization of metrics with an optional decision trigger overlay.
Supported operations
OperationDescription
list
List all resources of the specified type.
get
Get a single resource by ID.
create
Create a new resource. Decision create runs a two-step scaffold workflow that automatically resolves field and action names to UUIDs.
update
Replace a resource. Decisions and Dashboards are fully replaced on update.
delete
Delete a resource by ID. Business Object deletion cascades to all associated resources.
activate
Enable a Business Object (isActive=true) or decision (enabled=true).
deactivate
Disable a Business Object or Decision.
get-fields
Fetch a saved query's output field aliases. Use this before creating a query-sourced decision to ensure field names match exactly.
execute-adhoc
Run a one-off pipeline query without saving it.
verify-query
Execute a saved query and return results to confirm data is flowing.
check-action-log
Fetch recent action log entries for a Decision to confirm it fired correctly.
raw-snapshot
Return the most recent rows from a Business Object.
aggregate
Group and count Business Object data by field values.
field-health
Check which fields are populated vs. empty to detect JSONPath mismatches.
custom-query
Run a fully custom ad-hoc pipeline supplied in the pipeline argument.
publish-fake-data
Generate type-aware fake PubNub messages and publish them to a channel to test a Decision. Illuminate ingests messages with a 20–30 second delay.

:::tip Testing Decisions Use publish-fake-data to seed your Business Object with test data, wait 30 seconds, then run verify-query and check-action-log to confirm your pipeline is working end-to-end. :::

Sample prompts
List all my Illuminate Business Objects.
Set up Illuminate spam detection for my chat app.
Publish 10 test messages to verify my Illuminate Decision is firing.
Show me the action log for my spam detection Decision.

Insights analytics

These tools query PubNub Insights for read-only aggregated analytics from your PubNub account.

insights

Queries PubNub Insights aggregated analytics metrics for a keyset. Automatically routes to the correct endpoint based on the metric requested:

  • /v2/insights — aggregated metrics (unique channels, unique users, messages, device types, and more)
  • /v2/insights/top — ranked top-N metrics (top channels, top users, top message types)
API key and plan required

This tool requires a Service Integration API key with Account-level Insights Read permission. The key can be passed via the api_key parameter or set as PUBNUB_API_KEY in the environment (the same key used by manage_illuminate). Create or update the Service Integration in PubNub Portal → My Account → Organization Settings → API Management → Service Integrations.

Insights Premium tier is required. Free and Standard plans do not have API access. If you receive a 403 error, you may need to upgrade your plan.

* required
ParameterDescription
subscribe_key *
Type: String
Default:
n/a
PubNub subscribe key (sub-c-...) for the keyset to query. Falls back to PUBNUB_SUBSCRIBE_KEY env var.
metric *
Type: String
Default:
n/a
Insights metric to query. See the Metrics table below.
period *
Type: String
Default:
daily
Time grain: hourly, daily, weekly, or monthly. Not all periods are supported for all metrics. See the Period restrictions table below.
start_date *
Type: String
Default:
n/a
Inclusive start date in UTC (YYYY-MM-DD).
end_date *
Type: String
Default:
n/a
Inclusive end date in UTC (YYYY-MM-DD).
category
Type: String
Default:
n/a
Required for top-N metrics. Ranking dimension: by_messages, by_chats, by_subscribers, by_users_with_messages, by_users_with_chats, by_subscribed_channels, or all.
filter
Type: String
Default:
n/a
Filter expression for channel_patterns only (for example, startsWith:group. or eq:lobby). Do not use for top-N metrics — use filters instead.
filters
Type: String
Default:
n/a
JSON filter object for top-N metrics on /v2/insights/top. Top-level key must match the metric name. Value is an array of {field, operator, value} conditions (AND-combined). Operators: eq, neq, gt, lt, gte, lte, in, nin, startsWith.
orderBy
Type: String
Default:
n/a
Sort field and direction (for example, count_messages:desc).
limit
Type: Number
Default:
n/a
Maximum number of results to return.
api_key
Type: String
Default:
n/a
Service Integration API key override. Falls back to PUBNUB_API_KEY env var.
Available metrics
GroupMetricDescription
Channels
unique_channels
Count of unique channels with activity in the period.
Channels
unique_channels_combination
Overlap between channels with messages and channels used for chat.
Channels
percent_unique_channels_with_messages
Share of channels that had at least one message.
Channels
channel_patterns
Channel counts grouped by name prefix or exact match. Use with the filter parameter.
Channels (top-N)
top_20_channels
Top 20 channels ranked by the chosen category. Requires category.
Channels (top-N)
top_1000_channels
Top 1,000 channels ranked by the chosen category. Requires category.
Users
unique_users
Count of unique users (UUIDs) active in the period.
Users
unique_users_combination
Overlap between publishing and subscribing users.
Users
percent_unique_users_with_messages
Share of users who published at least one message.
Users
new_vs_recurring_users
New user count vs. returning user count. Does not support hourly.
Users
unique_users_by_country
Unique users broken down by country. Supports hourly and daily only.
Users (top-N)
top_20_users
Top 20 users ranked by the chosen category. Requires category.
Users (top-N)
top_1000_users
Top 1,000 users ranked by the chosen category. Requires category.
Messages
messages
Total message volume in the period.
Messages
message_by_country
Message volume broken down by country. Supports hourly and daily only.
Messages (top-N)
top_10_message_types
Top 10 message types by volume.
User behavior
avg_user_duration
Average user session duration. Supports hourly only.
User behavior
unique_users_by_duration_timeframe
Users bucketed by session length. Supports hourly only.
User behavior (top-N)
top_20_channels_with_user_duration
Top 20 channels ranked by total user time spent. Requires category. Supports hourly only.
User behavior (top-N)
top_1000_channels_with_user_duration
Top 1,000 channels ranked by total user time spent. Requires category. Supports hourly only.
Devices
publishes_by_device_type
Publish counts broken down by device type.
Devices
subscribers_by_device_type
Subscriber counts broken down by device type.
Devices
unique_users_by_device_type
Unique user counts broken down by device type.
Period restrictions
Period restrictions

Not all periods are supported for every metric. Passing an unsupported period returns an error.

PeriodSupported metrics
hourly only
avg_user_duration, unique_users_by_duration_timeframe, top_20_channels_with_user_duration, top_1000_channels_with_user_duration
hourly or daily only
All top_20_* and top_1000_* metrics, unique_users_by_country, message_by_country
daily, weekly, or monthly only (not hourly)
new_vs_recurring_users
All four periods
All remaining metrics
Sample prompts
Show me an Insights snapshot for my PubNub account for the last 7 days.
What are my top 20 channels by message volume today?
Show me new vs. recurring user trends for the last 30 days.
What devices are my subscribers using this week?
Show me channel activity for channels starting with 'team.' over the last month.

Resources

Resources provide read-only access to documentation through URI-based lookups.

pubnub_sdk_docs

Access PubNub SDK documentation.

PropertyValue
URI format
pubnub-docs://sdk/{language}/{feature}
Supported languages
22 programming languages
Supported features
13 feature categories
Sample URI
pubnub-docs://sdk/javascript/publish-and-subscribe

pubnub_chat_sdk_docs

Access PubNub Chat SDK documentation.

PropertyValue
URI format
pubnub-docs://chat-sdk/{language}/{feature}
Supported languages
JavaScript, Kotlin, Swift, Unity, Unreal
Supported features
40+ feature categories
Sample URI
pubnub-docs://chat-sdk/swift/messages-send-receive

Prompt templates

The MCP server includes pre-built prompt templates for common use cases which you can use as a starting point for your own prompts.

Healthcare and HIPAA compliance

Build secure, compliant chat applications using PubNub's Pub/Sub messaging, Presence, and App Context features.

hipaa-chat-short

Quick prompt to create a HIPAA-compliant chat application.

Generated prompt
Act as a senior software engineer and use PubNub MCP server to create a chat application for healthcare that is HIPAA compliant.

hipaa-chat-long

Detailed prompt for HIPAA-compliant chat with specific feature requirements.

Generated prompt
Act as a senior software engineer and use PubNub MCP server to create a chat application for healthcare that is HIPAA compliant, with Pub/Sub messaging for real-time chat, Presence for patient/doctor availability, and App Context for roles.

React development

react-app-short

Scaffold a basic React application with PubNub.

Generated prompt
Act as a frontend developer and use PubNub MCP server to scaffold a React app with Pub/Sub messaging and Presence.

react-app-long

Comprehensive React application with real-time features like Pub/Sub messaging, Presence, and App Context.

Generated prompt
Act as a frontend developer and use PubNub MCP server to scaffold a React app with Pub/Sub messaging for real-time updates, Presence to show when users are online or typing, and App Context to handle user metadata. Include sample React components for subscribing to a channel, publishing messages, and displaying presence indicators for active participants.

Gaming applications

Build multiplayer game lobbies using PubNub's Unity or Unreal SDKs.

gamelobby-short

Build a multiplayer game lobby with basic features.

Generated prompt
Act as a game developer and use PubNub MCP server to build a multiplayer lobby with chat and Presence indicators.

gamelobby-long

Advanced multiplayer lobby with team management.

Generated prompt
As a game developer, use PubNub MCP server to build a multiplayer game lobby that supports real-time chat using Pub/Sub, Presence for tracking when players come online or leave, and App Context for managing team assignments (e.g., red vs. blue team).

OEM and multi-tenant solutions

These prompts help with programmatic account management for OEM and multi-tenant use cases.

oem-client-management

Create apps and configure keysets for OEM (building resources used by someone else) client deployments.

Generated prompt
[OEM (building resources used by someone else)] As a developer, use PubNub MCP to create a new app, configure and assign keysets to clients.

multi-tenant-onboarding-short

Implement automated tenant onboarding for SaaS applications.

Generated prompt
[OEM] Act as a senior developer and use PubNub MCP server to implement automated tenant onboarding for a multi-tenant chat application in SaaS or healthcare industries.

multi-tenant-onboarding-long

Enterprise-grade multi-tenant onboarding with data isolation and error handling.

Generated prompt
Act as a senior developer and use PubNub MCP (which leverages Admin API for Keysets and Usage & Monitoring) to implement a multi-tenant chat application with automated tenant onboarding. The tenant Application will use: pubsub, History, App-Context, Presence For every new tenant or end-customer the application should: Create a new App (if required by your OEM model). Create and configure a new Keyset to ensure data isolation Make sure publish and subscribe keys are properly retrieved and propagated to the tenant's application as configuration variables The implementation should be fully automated, idempotent, and include error handling, and retries.

Illuminate analytics and automation

Use these prompts to set up Illuminate analytics and automation pipelines on top of your PubNub data.

illuminate-spam-detection

Set up a complete spam detection pipeline with escalating moderation actions for chat flooding and cross-posting.

Generated prompt
Act as a community moderator and use PubNub MCP to set up Illuminate spam detection. Start by asking: Is the concern chat flooding (one user sending too many messages in one channel), cross-posting (the same message sent to many channels), or both? For each pattern, copy the Illuminate Query Builder predefined template — do NOT invent custom query logic when a template fits. There is no programmatic 'create from template' helper; instead, list existing queries with `manage_illuminate {resource:'query', operation:'list'}`, find one tagged `meta.template: 'spam_cross_posting'` (or `'topn'` / `'advanced'`), GET it to read its pipeline shape, then create a new query with that pipeline shape adapted to the user's BO field UUIDs. First check whether a Chat-spam-shaped Business Object already exists on this keyset (typical fields: user, channel, message, message_type — these are commonly auto-provisioned when the PubNub Chat SDK is in use, so list BOs first; if a matching one is present, reuse it; only create a new BO if no suitable one exists, and ask the user to confirm field shapes if creating). Before creating anything, describe the detection approach in 1–2 sentences in plain English. Then show an escalating decision table with three severity rows: Low → notify moderator (quiet alert); Medium → notify + mute user in channel; High → notify + mute + ban user from channel. The mute/ban actions use `actionType: APPCONTEXT_SET_MEMBERSHIP_METADATA` with the appropriate operations array (see existing 'Decision for Cross Posting' in the account for shape); the notify action uses `actionType: PUBNUB_PUBLISH` to a moderation channel or `actionType: WEBHOOK_EXECUTION` to an external endpoint. Ask the user to confirm: (a) the time window (default: 60 seconds), (b) the message count or channel count thresholds for each severity level, and (c) which actions to enable per row. After confirmation: create the Business Object if not already active, copy the Query Builder template's pipeline shape into a new query, then create the Decision with the confirmed escalating rules and activate. CRITICAL for QUERY-sourced decisions: every inputFields[].name must exactly match the source query's output field alias (run get-fields on the query first; common aliases are 'user', 'channel', 'message_count', 'channel_count'). The handler now blocks name mismatches pre-flight, but using the right names from the start avoids the round-trip. Publish fake test data to verify the Decision fires correctly — use scenario:'chat-flooding' (count=20, single user/channel) for flooding rules and scenario:'cross-posting' (count=15, single user across channels) for cross-post rules. NOTE: if the keyset has Access Manager enabled, also pass `secret_key` (the keyset's secret key from Admin Portal → Keysets) — without it the publish returns a 403. Show the action log (per-decision endpoint; loop if multiple) to confirm fires.

illuminate-reward-engagement

Build an engagement reward pipeline for live events and gaming, including Top N ranking queries and per-user rate-limited reward decisions.

Generated prompt
Act as a live events manager and use PubNub MCP to set up Illuminate engagement rewards. Start by asking which participation behaviors to reward: poll answers, chat messages, reactions, or re-engaging low-engagement users (or a combination). For ranking rewards (Top N most chatty, Top N by reactions, Bottom N by engagement), copy the predefined Illuminate Query Builder template instead of inventing custom ranking logic. There is no programmatic 'create from template' helper; instead, list existing queries with `manage_illuminate {resource:'query', operation:'list'}`, find one tagged `meta.template: 'topn'`, GET it to read the pipeline shape, then create a new query with that pipeline shape adapted to the user's BO fields. For Bottom N (re-engagement), use the same topn template but reverse the orderBy direction (DESC -> ASC) on the count field. Before creating anything, describe the reward approach in 1–2 sentences in plain English. Then show a decision table: Poll answered → reward points or badge; Top N most chatty → Incentive A; Top N by reactions → Incentive B; Bottom N by engagement → Incentive C (re-engagement nudge). Ask the user to confirm: (a) which rows to enable, (b) the reward or incentive for each, (c) the evaluation window, and (d) a per-rule rate limit (default: once per day per user) to prevent duplicate rewards — translate this to `executionLimitType: 'ONCE_PER_INTERVAL_PER_CONDITION_GROUP'`, `executionLimitIntervalInSeconds: 86400`, and `executionLimitInputFieldIds: ['user']` (or the equivalent input field name on the decision; the handler resolves names to UUIDs automatically). After confirmation: create the Business Object capturing poll, chat, and reaction events (fields: user, channel, event_type). PRECHECK: list existing decisions and count those with sourceType='METRIC' — the account is hard-limited to 3 such decisions. If creating multiple per-behavior reward rules would push past the limit, consolidate them into multi-rule single decisions where possible. Create COUNT metrics — one per behavior being measured. Create a Dashboard with an engagement trend chart and active vs inactive user breakdown. Create the Decision(s) with the confirmed rules and rate limits, and activate. CRITICAL for QUERY-sourced ranking decisions (Top N / Bottom N): every inputFields[].name must exactly match the source query's output field alias (run get-fields on the query first; topn aliases are typically 'user', 'channel', 'message_count', 'rank_in_channel'). The handler now blocks name mismatches pre-flight, but using the right names from the start avoids the round-trip. Optionally: if the user wants an engagement drop alert, add a rule on the Chat Message Count metric using `operation: 'NUMERIC_LESS_THAN'` with the chosen threshold and an action that notifies moderators (PUBNUB_PUBLISH or WEBHOOK_EXECUTION). Publish fake test data with publish-fake-data (use scenario:'generic' with count=20 to spread events across users) to verify rewards fire correctly. NOTE: if the keyset has Access Manager enabled, also pass `secret_key` (the keyset's secret key from Admin Portal → Keysets) — without it the publish returns a 403. Show the action log per Decision (loop over decisions if more than one) to confirm.

illuminate-use-case

Guided setup of any Illuminate analytics and automation use case, from goal identification through build and validation.

Generated prompt
Act as a product manager and use PubNub MCP to set up a complete Illuminate use case. Follow this guided flow: Step 0 — Identify the goal. Ask: (1) What outcome do you want? Choose from: reward and incentivize desired behavior (e.g. most engaged users, high spenders, poll participants); prevent spam or abuse; alert when operational metrics like wait time or failure rates exceed normal; or automate live event or auction actions. (2) What should Illuminate do when the condition is met? Options: notify via webhook or channel message, reward or badge a user, mute or moderate a user, or trigger an external workflow. (3) How quickly should it react? Immediately on each event, near real-time every 1–5 minutes, or trend-based every 10–60 minutes. Step 1 — Choose the simplest implementation path: if the goal is spam (flooding or cross-posting) or ranking (Top N / Bottom N), start from a Query Builder template by listing existing queries with `manage_illuminate {resource:'query', operation:'list'}`, finding one with the matching `meta.template` tag (e.g. 'spam_cross_posting' or 'topn'), GET it to read its pipeline shape, then create a new query with that pipeline shape adapted to the user's BO field UUIDs (no programmatic 'create from template' helper exists — copy the shape). Otherwise use Metrics + Dashboard + Decision. Step 2 — Confirm data. Ask for one of: a sample event (JSON), a list of fields already in the payload, or where the data currently lives. Step 3 — Preview before building. Describe the automation in 1–2 sentences in plain English. Present the decision logic as a conditions → actions table with one rule per row. Ask for confirmation and threshold adjustments before creating any Illuminate resources. Step 4 — Build: create the Business Object (or confirm the existing one is active), create 1–3 Metrics for KPI visibility and tuning, create a Dashboard chart, then create and activate the Decision using the confirmed thresholds. PRECHECK: list existing decisions and count how many have sourceType='METRIC' — the account is hard-limited to 3 such decisions; if already at 3, either delete one or consolidate behaviors into multi-rule single decisions before creating more. CRITICAL for QUERY-sourced decisions: every inputFields[].name must exactly match the source query's output field alias (run get-fields on the query first and use those exact aliases — case-sensitive). Mismatched names cause the decision to silently never fire; the handler now blocks this pre-flight, but using the right names from the start avoids the round-trip. Step 5 — Validate: publish fake test data, check the dashboard and action log, and suggest threshold or rate-limit adjustments based on results. NOTE: if the keyset has Access Manager enabled, also pass `secret_key` (the keyset's secret key from Admin Portal → Keysets) to publish-fake-data — without it the publish returns a 403 with an actionable error pointing at the same fix.

illuminate-test-verify

Step-by-step test and verification of an existing Illuminate configuration.

Generated prompt
Act as a developer and use PubNub MCP to test and verify my existing Illuminate setup. 1. List all Business Objects and confirm the relevant one is active (isActive=true; if false, activate it before continuing). 2. Publish a small set of fake test messages (generic scenario, count=5) using publish-fake-data. NOTE: if the keyset has Access Manager enabled, also pass `secret_key` (the keyset's secret key from Admin Portal → Keysets) — without it the publish returns a 403; the tool will surface the AM error with the same fix suggestion. Wait 30 seconds for Illuminate ingestion. 3. Run a field-health query — flag any fields with populated=0 or with `sampleValues` containing only empty strings as potential JSONPath mismatches (every jsonPath should start with `$.message.body.`). On a brand-new BO, field-health is only meaningful AFTER step 2's publish has been ingested, which is why it follows the publish here. 4. Run a raw-snapshot query (limit=10) to confirm messages are being captured with the right shape. 5. List all saved queries; for any used as a Decision source, run verify-query to confirm the query returns rows for the time window it covers (an empty result here is the most common reason a QUERY decision doesn't fire). 6. List all decisions, filter to enabled=true, then for EACH active Decision call check-action-log (the endpoint is per-decision; loop over them). Report fires per decision over the last hour. Report any issues found and suggest fixes. If a QUERY-sourced Decision shows zero fires despite verify-query returning matching rows, check that every inputFields[].name on the Decision exactly matches a query output alias from get-fields (case-sensitive) — silent name mismatches are the #1 cause. If Decisions are firing too frequently or not at all, suggest adjustments to time window, thresholds, filters, and execution rate limits (executionLimitType, executionLimitIntervalInSeconds, executionLimitInputFieldIds).

Insights analytics

Use these prompts to query PubNub Insights analytics metrics for your keyset.

insights-snapshot

Quick high-level analytics snapshot for a date range, including unique channels, unique users, message volume, and top channels — with anomaly callouts.

Generated prompt
Act as an analytics engineer and use PubNub MCP to produce an Insights snapshot for my account. Step 0 — Confirm inputs: (1) the subscribe key to query, (2) the date range (default: last 7 days, ISO 8601 in UTC), and (3) the time grain (default: daily). If the user does not have an Insights API key, point them to the how-to guide for getting Insights API access. Step 1 — Use the `insights` tool to query four metrics in parallel for the confirmed date range and grain: `unique_channels`, `unique_users`, `messages`, and `top_20_channels` with `category=by_messages`. Note that `top_20_channels` requires `period=hourly` or `period=daily` only — never `weekly` or `monthly`. Step 2 — Present the results in this order: (a) a one-line headline with the date range and the trend in unique users (e.g. "+12% week-over-week"), (b) a table of daily unique users / unique channels / messages, (c) the top 20 channels by message volume with their counts. Step 3 — Call out anomalies: any day with more than ±30% deviation from the period average, any channel that appears in the top 20 with more than 50% of total volume, or any drop in unique users greater than 20% day-over-day. Step 4 — Suggest 2–3 follow-up queries the user might want to run (e.g. "Want to see new vs recurring user breakdown?" or "Want to see the top message types?"). Always include the date range and timezone (UTC) in the response so the user has unambiguous framing.

insights-channel-analysis

Deep dive into top channels by ranking category, channel naming patterns, and cross-category engagement comparisons.

Generated prompt
Act as a product analyst and use PubNub MCP to analyze top channels in detail. Step 0 — Confirm inputs: (1) subscribe key, (2) date range (default: last 7 days, UTC), (3) time grain (`hourly` or `daily` only — top metrics do not support weekly or monthly), and (4) which ranking categories to include (default: `by_messages`, `by_subscribers`, and `by_users_with_messages`). Step 1 — Use the `insights` tool to query `top_20_channels` for each requested category. Step 2 — Cross-reference the rankings: list channels that appear in all three categories (high engagement and high reach), channels that have many messages but few subscribers (chatty but small), and channels that have many subscribers but few messages (broadcast-style). Step 3 — If the user asks about a channel naming pattern (e.g. "channels starting with team." or "all room.* channels"), use the `channel_patterns` metric with a `filter=startsWith:` expression instead of post-filtering top-N results. Step 4 — Optionally query `unique_channels_combination` to show overlap between message-publishing channels and chat-publishing channels, and `percent_unique_channels_with_messages` to show how many of the keyset's channels actually had messages in the period. Step 5 — Present results as: (a) a unified ranking table with all categories side-by-side, (b) the cross-category insights from step 2, (c) any pattern-based subtotals from step 3, and (d) 2–3 follow-up actions (e.g. "Want to look at user duration on these channels?"). Important: top-N counts cannot be summed across periods — when showing daily rankings, present one ranking per day rather than aggregating.

insights-user-growth

New vs. recurring user trends, daily/weekly/monthly breakdowns, top countries, and whale user identification.

Generated prompt
Act as a growth analyst and use PubNub MCP to track user growth on my PubNub account. Step 0 — Confirm inputs: (1) subscribe key, (2) date range (default: last 30 days, UTC), and (3) trend grain (`daily`, `weekly`, or `monthly` — note that `new_vs_recurring_users` does NOT support `hourly`). Step 1 — Use the `insights` tool to query in parallel: `unique_users` for the chosen grain, `new_vs_recurring_users` for the chosen grain, and `unique_users_by_country` (which only supports `hourly` or `daily`). Step 2 — Compute and present: (a) the headline week-over-week or month-over-month change in unique users, (b) the new-user count and the recurring-user count per period with a small chart-style table, (c) the new-to-recurring ratio (a healthy product typically has 20–40% new users in any given period), and (d) the top 10 countries by unique user count from `unique_users_by_country`. Step 3 — Call out: any period where new users dropped more than 30% from the prior period (acquisition issue), any period where recurring users dropped more than 20% (retention issue), and any geography that suddenly appears or disappears in the top 10 (potential market change or fraud). Step 4 — Optionally query `top_20_users` with `category=by_messages` to identify your most active users (whales), and `percent_unique_users_with_messages` to show the publish-vs-subscribe-only user split. Step 5 — Suggest 2–3 follow-up queries (e.g. "Want to see what channels new users are joining?"). Always frame results with the date range and UTC timezone.

insights-engagement-deep-dive

Average user duration, session-length bucket histogram, top channels by user-minutes, and device-type breakdown.

Generated prompt
Act as a product analyst and use PubNub MCP to do an engagement and device deep dive. Step 0 — Confirm inputs: (1) subscribe key, (2) date range (default: last 24 hours for duration metrics, last 7 days for device metrics, all UTC), (3) for duration metrics, use `period=hourly` (the ONLY supported period for duration). For device metrics, use `period=daily` by default. Step 1 — Use the `insights` tool to query duration metrics: `avg_user_duration` (hourly), `unique_users_by_duration_timeframe` (hourly — bucketizes users by session length), and `top_20_channels_with_user_duration` (hourly, top channels ranked by total user time spent). Step 2 — Use the `insights` tool to query device metrics: `publishes_by_device_type`, `subscribers_by_device_type`, and `unique_users_by_device_type`. Step 3 — Present results in this order: (a) average user duration trend across the chosen window, (b) duration bucket histogram (e.g. < 1 min, 1–5 min, 5–30 min, 30+ min), (c) top 20 channels ranked by total user-minutes, (d) device-type table with publishes / subscribers / unique users side-by-side and percent share for each device type. Step 4 — Insight callouts: channels with high user-duration but low message volume (lurker / read-only channels), unusual device-mix shifts (e.g. mobile share dropping or web share spiking week-over-week), and the channel with the highest engagement-per-user ratio (total duration / unique users). Step 5 — Suggest 2–3 follow-up queries (e.g. "Want to see device split for top channels only?"). Always frame results with the time window and UTC timezone, and remind the user that duration metrics are only available at hourly grain.