How PyRIT's WebSocket target red teams a custom chat protocol
If your chat product streams over a custom WebSocket protocol, PyRIT's WebsocketTarget is the supported way to red team it. You configure it with the service-specific initialisation messages, a prompt builder that turns each PyRIT prompt into the frame your service expects, and a response parser that extracts the reply text from the frames that come back. Once those three pieces match your protocol, PyRIT can send attack prompts through the same channel your users use, so the results reflect the real chat path rather than a simplified API that sits beside it.
The integration only handles the transport and the framing. It does not discover your protocol for you, and it does not decide whether an answer is harmful; that is the job of PyRIT's scorers. Your team has to capture a real session, confirm which messages must be sent before the first prompt (authentication, session setup, model selection), and check that the parser ignores typing indicators, heartbeats and tool events so that only the answer text is scored. Ask the engineers who own the chat service which frames carry state and which can be dropped, because a parser that mistakes a status frame for a reply will produce false results.
Multi-turn attacks need one more piece. If a connection drops partway through an attack, PyRIT cannot rebuild the conversation history on its own, so you must supply a restore callback that opens a replacement connection and re-establishes the session. Without that callback the target fails rather than silently losing history, and it does not retry a prompt whose connection failed. Plan for that failure mode: decide who owns the callback, test how your service handles reconnection and session expiry, and record failed prompts as incomplete rather than as passed tests, so a dropped connection never looks like a clean result.
What you need before connecting PyRIT to a WebSocket service
Before writing any WebSocket target configuration, confirm the PyRIT host, the service's message format, network path, test credentials and connection lifecycle. Each of these shapes the initialisation messages, the prompt builder and response parser, and whether multi-turn attacks can survive a dropped connection.
PyRIT installed on a supported Python
Install PyRIT from PyPI with pip. The PyPI package supports Python 3.10 up to but not including 3.15, and the PyRIT documentation recommends Python 3.13, so pin a version in that range on the host that will run attacks. Record the exact PyRIT version in your test plan, because the WebSocket target's configuration interface and the scoring setup can change between releases. Check the version in the release notes before you copy examples from older tutorials.
WebSocket target docsA documented or captured message format
The WebSocket target needs exact knowledge of what the service expects. Collect the initialisation messages sent after connecting, the structure of a user prompt, and the shape of streamed or final responses. Use the vendor's protocol documentation where it exists, or capture a real session from browser developer tools or a proxy you are authorised to use. Without this, the prompt builder and response parser will be guesses, and failures will look like model refusals.
Network reachability and TLS trust
Confirm that the PyRIT host can open a WebSocket connection to the service's endpoint, including any proxy, firewall or load balancer rules that apply to the WebSocket upgrade. If the service uses a private certificate authority, install that CA in the trust store used by the PyRIT runtime and verify the handshake from that exact host before any attack runs. A test that fails at the TLS layer produces no useful signal about the model.
Test credentials and session tokens
Obtain a dedicated test account with the same role a real user would have, not an administrator account. Find out whether authentication is a bearer token in the handshake, a cookie, or a token sent in the initialisation message, and how long each token lasts. Store secrets in the PyRIT environment file or your secrets manager, not in the target script, and confirm who owns rotation for the test account during the engagement.
Access to the connection lifecycle
Ask the service owner how connections close, time out and reconnect. Find out whether the server closes idle sockets, whether it issues a new session identifier after reconnection, and whether conversation state lives on the server or in the client. This determines whether you need a restore callback for multi-turn attacks. Also confirm that you can reproduce a dropped connection in a test environment, so you can check that PyRIT fails cleanly rather than losing history.
How a prompt travels through the WebSocket target
The walk starts in a PyRIT attack, which hands the objective to the prompt builder that shapes the message for the service. The WebSocket target then opens the connection, sends the service-specific initialisation messages and the prompt, and passes the raw reply to the response parser, which returns text to PyRIT memory. The dashed boundary marks where traffic leaves your PyRIT host. Check the branch for a dropped connection: with a restore callback the target rebuilds history, and without one the attack fails rather than losing turns silently.
Prompt flow through the WebSocket target, with the trust boundary to the chat service.
Configuring the WebSocket target step by step
This sequence takes a team from a captured handshake to a verified WebSocket target that can run both single-turn and multi-turn tests against the service. Each step ends with a check so that failures are found at the point where they are introduced.
Capture and document the protocol handshake
Someone with access to the service and its client code records how a normal session starts: the connection URL, any headers or tokens sent on connect, the order of initialisation frames, and the frame shapes for a user message and a reply. Browser developer tools or a logging proxy in a test environment are usual ways to capture this. Write the findings down as a short protocol note that the rest of the steps reference. The step is done when someone other than the author can replay the handshake by hand and get a valid session.
Write the initialisation messages
From the protocol note, write the messages the service expects before it accepts a prompt, such as an authentication frame, a session or channel selection, or a configuration message. Keep each message as the exact structure the service sends, including any fields that must be present but empty. Confirm with the service owner which messages are required and which are optional. The check is a connection that reaches the state where the service is ready to take a prompt, without any manual steps.
Write the prompt builder
Write the function that turns a PyRIT prompt into the outbound frame the service expects, using the field names and nesting from the protocol note. For multi-turn work, confirm whether the service expects the full conversation history in each frame or only the latest message, because this determines what the builder must include. Run the builder against one sample prompt and compare its output byte for byte with a frame captured from the official client. The check is an identical frame for the same input.
Write the response parser
Write the function that extracts the reply text from incoming frames. Services often send typing indicators, heartbeats, acknowledgements and status updates alongside the answer, so the parser must return only the content frame and ignore control frames without raising errors. Test it against recorded frames, including a refusal and an error frame, to confirm each one is handled as intended. The check is a parser that returns the expected reply text for every recorded sample and nothing for control frames.
Configure the target with environment credentials
Set the endpoint URL and any credentials in the PyRIT environment file at ~/.pyrit/.env, not in the attack script, and reference them from the target configuration. Pass the initialisation messages, prompt builder and response parser to the WebSocket target. Confirm with your security team how the credential is scoped and rotated, since it will be read by every run on that machine. The check is a target object that instantiates without errors and reports its endpoint without printing the secret.
Add a restore callback for replacement connections
Provide a restore callback that opens a replacement connection and replays the required initialisation and conversation state when the original socket drops during a multi-turn attack. PyRIT's WebSocket target fails instead of silently losing history when no restore callback is set, so this step is what allows long attacks to continue after a reconnect. Test the callback by forcing a disconnect mid-conversation in a test environment. The check is that the next turn after the reconnect receives a reply that depends on earlier turns, which confirms the history was restored.
Run a single-turn smoke test
Send one benign prompt through the target with a PyRIT attack that does a single turn, then open the memory store and confirm that the prompt, the outbound frame, and the parsed reply were all recorded. Use a harmless objective so that a failure points to the integration rather than to the model's refusal behaviour. The check is a stored conversation whose assistant message contains the parsed reply text and no control frame content.
Run a multi-turn smoke test
Run a short multi-turn attack of two or three turns in which a later prompt depends on an earlier answer, such as asking the service to recall a detail it was given. Include one forced reconnect with the restore callback active. Review the stored conversation in memory to confirm every turn was recorded in order and the later reply shows it had the earlier context. The check is a complete multi-turn conversation in memory after the reconnect, which is the condition to meet before running the full attack set.
How chat messages, roles and session state map to PyRIT
This table pairs each part of a WebSocket chat protocol with the PyRIT concept it maps to, so you can check the mapping against your own captured traffic. Read each row as a question to answer from the frames you see, not as a field name to assume. The main takeaway is that session identifiers and tokens need explicit handling, because a wrong mapping here shows up as lost multi-turn history.
| Service element | PyRIT concept | What to confirm in captured traffic |
|---|---|---|
| User prompt frame | Prompt request piece sent through the prompt builder | Which outbound frame carries the user text, and whether it is one frame or several |
| Assistant reply frame | Response piece parsed by the response parser | Which inbound frame carries the final answer, and how streamed chunks signal completion |
| Role labels (user, assistant, system) | Roles stored on each message in conversation history | Whether the service uses explicit role fields or implies roles from frame type |
| Initialisation messages | Setup frames sent once when the connection opens | Which frames must be sent before the first prompt, and in what order |
| Session or conversation ID | Conversation ID used to group turns in memory | Where the ID is issued, whether it changes per connection, and whether the service expects it in each frame |
| Authentication token | Header or initialisation value supplied from your environment file, not stored in memory results | Where the token travels, its expiry, and whether a reconnect needs a fresh token |
| Prior turns in history | Conversation history replayed by PyRIT for multi-turn attacks | Whether the service keeps history server-side or expects the client to resend it |
| Memory records | Conversations and results stored in SQLite or Azure SQL | That stored turns match what the service showed, so an assessor can follow each attack |
Why multi-turn attacks depend on the connection restore callback
A dropped WebSocket connection in the middle of a multi-turn attack is a data integrity problem, not just an availability problem. If the service silently accepts a replacement connection with an empty or partial conversation, the next prompt arrives in a context the attack never built, and every later response is scored against a history the team did not design. PyRIT's WebsocketTarget is documented to avoid this: without a restore callback for replacement connections, it fails rather than silently losing multi-turn history. Treat that failure as a feature. It tells you the attack's results are no longer trustworthy from that point onward.
The restore callback is where your team decides what the service needs to see before the next prompt. Start from the service's own protocol: which initialisation messages establish a session, whether the server keeps conversation state or expects the client to resend prior turns, and which identifiers tie a turn to a session. Then confirm with the service owner which of those the replacement connection must re-send, and test the callback against a deliberately interrupted conversation. Compare the reconstructed history with the one PyRIT's memory holds for that conversation. Any gap you find is a callback defect, and it should be fixed before any attack results are used as evidence.
Because the target does not retry a prompt whose connection failed, the operator owns recovery. Record each failed prompt in PyRIT memory with its conversation identifier, turn number and failure reason, so the failure is visible in later results rather than hidden as a missing response. Then rerun only from the last turn the service confirmed, using a fresh conversation if the restored history cannot be verified. Record which runs were rerun and why. An auditor reviewing multi-turn results will ask whether any reported success depended on an interrupted conversation, and this log is the only way to answer that accurately.
Securing the WebSocket test setup
A WebSocket target sends real prompts and real session tokens to a live chat service, so the test setup itself needs the same care as the service under test. The cards below cover where credentials live, how much the test account can reach, where conversations are stored, and which hosts the target is allowed to contact.
Keep credentials in the PyRIT environment file
PyRIT reads credentials from ~/.pyrit/.env, so the WebSocket endpoint details and any session tokens used in initialisation messages belong there rather than in the target script or in shared notebooks. Confirm that the file is readable only by the account running the test, that it is excluded from version control, and that tokens are rotated after each engagement. Use a dedicated file per environment so a staging token never reaches production.
Scope the test account to the chat role
The account the target uses should hold only the permissions a normal end user has in the chat product, with no admin, export or tool-enabling rights. Ask the service owner which roles the test account can reach and whether its conversations are visible to other users. A narrowly scoped account also limits the damage if an attack prompt causes the service to take an action on that account's behalf.
Keep traffic and memory under team control
PyRIT memory stores conversations and results in SQLite or Azure SQL, so the database location becomes a record of every adversarial prompt and every reply the service produced. Choose a storage location your team operates, restrict read access to the people on the engagement, and set a retention rule before the first run. Confirm where logs of WebSocket frames are written, since captured replies can contain personal data from the service.
Verify TLS certificates on every connection
A WebSocket target that connects over wss:// should verify the server certificate against your trusted authority, not skip verification to get a test running. Disabling checks can send session tokens and test prompts to an impostor endpoint without any warning. Confirm the certificate chain for the test host with the service owner, and treat any certificate error as a stop condition until it is explained.
Limit the hosts the target can reach
Apply network egress rules so the machine running PyRIT can open connections only to the WebSocket host under test and to the model services the scorers and attack models need. Confirm this with the network team before the run, and test that connections to unlisted hosts fail. An allowlist also prevents a misconfigured endpoint from sending test traffic to a production system or a third-party service.
Report PyRIT vulnerabilities privately
If testing shows that PyRIT itself behaves unsafely, such as leaking credentials into logs or mishandling a connection, report it privately through the Microsoft Security Response Center under the project's security policy rather than in a public issue. Keep the report to reproduction steps and affected versions, and do not publish exploit details until the maintainers have responded. Record the PyRIT version in use with the test results so any report can be matched to a release.
PyRIT repositoryFailures when PyRIT talks to a WebSocket service
This table lists the failures teams most often hit when PyRIT's WebSocket target talks to a custom chat service, with the likely cause, what to check and the fix for each. Work through it in order during the first connection test, since the early rows block the later ones. Items marked as things to confirm depend on your service's own protocol documentation.
| Failure | Likely cause | What to check | Fix |
|---|---|---|---|
| Initialisation message rejected | The init messages do not match the protocol the service expects, such as a missing auth token, wrong field names or a wrong order | Capture a working browser session's WebSocket frames and compare them with the configured init messages, in order | Correct the init messages to match the captured sequence, and add any handshake step the service requires before the first prompt |
| Parser returns empty text | The response parser reads a field that is absent in the reply, or the service sends the answer in a later frame | Log raw frames received for one prompt and identify which frame carries the answer text | Update the parser to select the answer frame and field, and skip frames that carry no text |
| Parser returns control frames | Ping, typing indicator, acknowledgement or status frames are treated as the model reply | Count frame types per prompt and note which ones arrive before the final answer | Filter on the message type that marks a completed answer, and ignore heartbeat and status frames |
| Prompt builder encoding mismatch | The service expects escaped JSON, a different key name or a text encoding that the builder does not produce, so the server reads the prompt incorrectly | Send one prompt with special characters and quotes, and compare the echoed text with what was sent | Adjust the builder's serialisation and key names, and test with a prompt that contains quotes, newlines and non-ASCII characters |
| Connection dropped mid-conversation | The server closes idle or long sessions, or a network device resets the socket between turns, and no restore callback is configured | Note the turn number at which the drop occurs and check the server's session timeout and any proxy idle limits | Configure a restore callback that opens a replacement connection and replays the session state the service needs; without it, the target fails instead of losing history |
| Prompt not retried after a connection failure | The target does not resend a prompt whose connection failed, by design, so the attack records a gap | Check the run's memory for a failed turn with no reply and confirm the attack stopped or moved on | Rerun the affected objective from the start, or resend the turn in your own driver code after the connection is restored and confirm the history is consistent |
| Timeouts on streamed replies | The reply streams over many frames and the target's wait limit ends before the final frame arrives, or a long answer exceeds it | Time the gap between the first and last frame for a long prompt and compare it with the configured timeout | Increase the response timeout for this service, and make the parser end on the explicit completion frame rather than on a fixed delay |
| Certificate errors | The service uses an internal certificate authority or a self-signed certificate that the Python runtime does not trust | Confirm the certificate chain with your platform team and test the connection outside PyRIT with the same CA bundle | Provide the internal CA bundle to the Python environment, and avoid disabling verification; treat any skipped check as a finding to record |
Questions teams ask before red teaming a WebSocket chat service
How long does a WebSocket red teaming integration take?
No duration is supplied for this work, so confirm timing against your own environment rather than a generic figure. The main drivers are how many message types the protocol uses, how initialisation works (for example, whether a session needs a handshake, a token or a model selection message before the first prompt), how the response is structured, and how reconnects behave. A service with one prompt message and one streamed reply type is far quicker to wire up than one with authentication refreshes, typing indicators, tool-call events and session tokens that expire mid-conversation. Ask for the time estimate to be broken into protocol mapping, parser build, multi-turn restore testing and failure testing.
What does the client need to provide before work starts?
The work depends on having an accurate picture of the protocol and a safe place to test it. Expect to provide:
- Protocol documentation, or captured WebSocket traffic from a test session showing initialisation, prompt, streaming and error messages
- Test accounts with the same permissions as real users, plus any API keys or tokens the service needs, handled through your normal secrets process
- A non-production or staging environment, with rate limits and logging that match what you intend to test
- A named contact who can explain undocumented message types and confirm which behaviours are bugs and which are design
Agree in writing whether the test may trigger moderation, account lockouts or billing events.
Can an internal team set this up without a partner?
Yes, if the team has engineers comfortable with Python, asynchronous WebSocket clients and the target's protocol. PyRIT's WebSocket target is configured with service-specific initialisation messages, a prompt builder and a response parser, so the core work is writing those three pieces against your protocol. The harder parts are usually the ones teams underestimate: restoring a connection mid-conversation, deciding what happens when a prompt fails, and proving that multi-turn attacks really carried the earlier history. A partner is most useful when the team lacks time, when the protocol is poorly documented, or when they want an independent test with a findings report and retest.
What does a partner quote depend on?
A quote follows from a written scope, so the inputs that move it are the ones that define the work. Ask how each of the following is priced: the number of message types and how many need custom handling, whether the service needs an authentication or session flow, how many attack types and turn lengths are in scope, whether a restore callback must be built, how much of the test runs in your environment versus a staging copy, and whether results are delivered as a one-off report or with a retest. Fees are one-time for the build and test, while any ongoing scheduled testing or protocol-change maintenance is usually a recurring item to confirm separately.
Is a restore callback required for single-turn tests?
No. A restore callback matters for multi-turn attacks, where the conversation history must survive a dropped connection. For single-turn prompts, each request stands on its own, so a connection that is replaced between prompts does not lose context that the attack depends on. You still need a working initialisation sequence and a reliable response parser. Confirm that your single-turn test does not secretly depend on earlier turns, such as a session that remembers a prior instruction, because that dependency would make a single-turn result misleading.
What happens when a prompt fails because the connection dropped?
The WebSocket target fails rather than silently losing multi-turn history, and it does not retry a prompt whose connection failed. Without a restore callback for replacement connections, a dropped connection during a conversation stops the run instead of continuing with a damaged history that would produce misleading scores. Your team then decides whether to rerun the affected attack from the start, which keeps results clean. Plan retry logic at the orchestration level so that failed prompts are logged, marked as incomplete in results and not counted as passed or failed.
Does the WebSocket connection need encryption and access control during testing?
Yes. Connect only over a secured WebSocket endpoint, keep tokens and session credentials out of source control and load them from your secrets store, and restrict which hosts the test runner can reach. Test traffic often contains sample sensitive prompts and model outputs, so store PyRIT memory in a location with the same access controls as your other test records. Confirm the service's own terms allow automated adversarial testing before you start.
What the team owns after the first working connection
The first working connection is not the end of the work. The team owns the WebSocket parser and initialisation messages for as long as the target is in use, and those are the parts most likely to break silently. When the chat product changes its handshake, message envelope or response structure, the prompt builder may still send messages that are accepted but the response parser may start returning empty or partial text. Assign a named owner for the target configuration, keep the initialisation messages and parser in version control next to the test code, and record which product build each configuration was last checked against. Ask the product owner for advance notice of protocol changes, and treat any unannounced change as a reason to rerun the checks below.
Rerun the smoke test after every upgrade, whether the chat product, the PyRIT installation or the Python runtime changed. The PyRIT project's current release is v1.1.0, released on 4 September 2026, and the WebSocket target's behavior should be confirmed against the PyRIT documentation for the exact version your team runs before you trust results from a new installation. Check that a single-turn prompt returns the expected reply, that a multi-turn conversation keeps its history after a forced reconnect, and that the restore callback still produces a usable connection. Keep the output of each smoke run so a regression can be compared with the last known good state.
Stored conversations are records of sensitive test traffic, and the team must review them under its own data controls. PyRIT's memory keeps prompts and responses in SQLite or Azure SQL, so decide where that database lives, who can read it, how long it is retained and how it is deleted. Confirm with your security and privacy teams whether captured chat content from the product, including any user data it contains, is permitted in the memory store. Review a sample of stored conversations after each test cycle to confirm the parser is capturing full replies and that no unexpected data is being logged, and document the review so the evidence trail is clear.
How DeployOpen scopes and delivers a PyRIT WebSocket integration
DeployOpen approaches a PyRIT WebSocket integration as a written, fixed-scope piece of work. We start from the chat service's actual message flow, agree what the target must reproduce, and build and document the connector in an environment you control. The result is a target your security team can rerun and review.
How we scope
- Map the service's WebSocket handshake, initialisation messages and message shapes before agreeing any build work.
- Agree in writing which chat flows, multi-turn behaviours and reconnection cases the target must handle.
- Confirm with your team how connections are restored, since restore behaviour decides whether multi-turn attacks can run.
How we build
- Configure the initialisation messages, prompt builder and response parser against captured traffic from a test environment.
- Implement a restore callback for replacement connections so multi-turn history is kept rather than silently lost.
- Test failure behaviour directly, confirming that a prompt whose connection failed is recorded as failed and not retried.
How we hand over
- Deliver the target code, configuration and environment variables with a runbook for your engineers.
- Document the protocol assumptions, restore logic and known failure modes so reviewers can trace each result.
- Walk your red team and security engineers through a sample run and the memory records it produces.
How we support
- Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
- Ongoing support, upgrades and continuous testing are available as a retainer when the chat service changes.
- Re-verify the target after protocol or message format changes on the service side, and confirm the scope of each update in writing.

