Modify the API key permissions and turn on the Agent Gateway toggle for your API key. See the Quickstart for where to configure this in the app. Make sure the
agents.invoke scope is enabled.Introduction
The Quickstart guide provides a basic example of how to use the Agent Gateway. This guide provides more examples and code snippets to help you get started.Fetching the agent card
curl --location --request POST 'https://agents.portkey.ai/v1/agent/{agent-slug}/.well-known/agent.json' \
--header 'Content-Type: application/json' \
--header 'x-portkey-api-key: {PORTKEY_API_KEY}'
import asyncio
import json
from a2a.client import A2ACardResolver
import httpx
BASE_URL = "https://agents.portkey.ai/v1/agent/{agent-slug}"
API_KEY = "{PORTKEY_API_KEY}"
async def log_httpx_request(request: httpx.Request) -> None:
try:
body = request.content.decode("utf-8") if request.content else "<empty>"
except Exception:
body = "<streaming or unreadable body>"
print(f"[httpx] {request.method} {request.url}")
print(f"[httpx] body: {body}\n")
async def main() -> None:
print(f"Fetching agent card from {BASE_URL}...")
async with httpx.AsyncClient(
base_url=BASE_URL,
headers={"x-portkey-api-key": API_KEY},
event_hooks={"request": [log_httpx_request]},
) as client:
resolver = A2ACardResolver(httpx_client=client, base_url=BASE_URL)
agent_card = await resolver.get_agent_card()
print(json.dumps(agent_card.model_dump(mode="json", exclude_none=True), indent=2))
if __name__ == "__main__":
asyncio.run(main())
import {
DefaultAgentCardResolver,
ClientFactory,
ClientFactoryOptions,
} from "@a2a-js/sdk/client";
const BASE_URL = "https://agents.portkey.ai/v1/agent/{agent-slug}";
const API_KEY = "{PORTKEY_API_KEY}";
class HeaderAuthInterceptor {
async before(args) {
args.options = {
...args.options,
serviceParameters: {
...(args.options?.serviceParameters || {}),
"x-portkey-api-key": API_KEY,
},
};
}
async after() {}
}
function createAuthenticatedFetch() {
return async (input, init = {}) => {
const headers = new Headers(init.headers || {});
headers.set("x-portkey-api-key", API_KEY);
return fetch(input, { ...init, headers });
};
}
async function main() {
console.log(`Fetching agent card from ${BASE_URL}...`);
const authFetch = createAuthenticatedFetch();
const resolverBaseUrl = BASE_URL.endsWith("/") ? BASE_URL : `${BASE_URL}/`;
const options = ClientFactoryOptions.createFrom(
ClientFactoryOptions.default,
{
cardResolver: new DefaultAgentCardResolver({
fetchImpl: authFetch,
}),
clientConfig: { interceptors: [new HeaderAuthInterceptor()] },
},
);
const factory = new ClientFactory(options);
const client = await factory.createFromUrl(resolverBaseUrl);
const card = client.agentCard;
if (!card) {
throw new Error("Unable to read agent card from SDK client instance.");
}
console.log(JSON.stringify(card, null, 2));
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
Invoking the agent
JSON-RPC examples
cURL
curl --location 'https://agents.portkey.ai/v1/agent/{agent-slug}' \
--header 'Content-Type: application/json' \
--header 'x-portkey-api-key: {PORTKEY_API_KEY}' \
--data '{
"jsonrpc": "2.0",
"id": "req-1",
"method": "tasks/send",
"params": {
"id": "task-header-1",
"message": {
"role": "user",
"parts": [
{
"type": "text",
"text": "echo Hello from header auth"
}
]
}
}
}'
python
import asyncio
import json
from uuid import uuid4
import httpx
BASE_URL = "https://agents.portkey.ai/v1/agent/header-based-authentication"
API_KEY = "+/gW5Oclr7Y9z01jEOVBaAfKZxfz"
async def log_httpx_request(request: httpx.Request) -> None:
try:
body = request.content.decode("utf-8") if request.content else "<empty>"
except Exception:
body = "<streaming or unreadable body>"
print(f"[httpx] {request.method} {request.url}")
print(f"[httpx] body: {body}\n")
async def main() -> None:
print(f"Connecting to A2A agent at {BASE_URL}...")
message_text = "echo Hello from header auth"
task_id = f"task-{uuid4().hex[:12]}"
request_id = f"req-{uuid4().hex[:8]}"
payload = {
"jsonrpc": "2.0",
"id": request_id,
"method": "tasks/send",
"params": {
"id": task_id,
"message": {
"role": "user",
"parts": [
{
"type": "text",
"text": message_text,
}
],
},
},
}
async with httpx.AsyncClient(
base_url=BASE_URL,
headers={
"x-portkey-api-key": API_KEY,
"Content-Type": "application/json",
},
event_hooks={"request": [log_httpx_request]},
) as httpx_client:
print(f"Sending task with message: {message_text}")
response = await httpx_client.post("", json=payload)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
if __name__ == "__main__":
asyncio.run(main())
JavaScript
const BASE_URL =
process.env.BASE_URL || "https://agents.portkey.ai/v1/agent/{agent-slug}";
const API_KEY = process.env.API_KEY || "{PORTKEY_API_KEY}";
const MESSAGE_TEXT = process.env.MESSAGE_TEXT || "echo Hello from header auth";
async function main() {
console.log(`Connecting to A2A agent at ${BASE_URL}...`);
console.log(`Sending task with message: ${MESSAGE_TEXT}`);
const payload = {
jsonrpc: "2.0",
id: `req-${crypto.randomUUID().slice(0, 8)}`,
method: "tasks/send",
params: {
id: `task-${crypto.randomUUID().slice(0, 12)}`,
message: {
role: "user",
parts: [{ type: "text", text: MESSAGE_TEXT }],
},
},
};
const response = await fetch(BASE_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-portkey-api-key": API_KEY,
},
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(
`HTTP ${response.status}: ${response.statusText} while calling tasks/send`,
);
}
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
Further reading
Quickstart
Get started with the Agent Gateway by registering your first agent.
Agent Registry
Manage your agent integrations and control access to agents and their skills.
Agent Servers
Learn how virtual agent servers work and how to host your own.

