Guide
Semgrep Guardian in Claude Code cloud sessions, signed in through company SSO
How a large enterprise gave every Claude Code cloud session Semgrep Guardian, with each developer signed in through company SSO and no shared token: the setup script and the two-link sign-in.
Chris Baran
Project work · · 7 min read
On this page
AI coding assistants write more and more of a team’s new code. The cheapest moment to catch a security flaw in that code is the moment it’s written, before anyone commits it. Semgrep Guardian does exactly that: a plugin that scans each file an AI agent writes and hands any findings straight back to the agent to fix.
A large enterprise wanted Guardian wherever its developers used Claude Code. Some of them work in Claude Code on the web, where each session runs in a short-lived cloud container rather than on their machine. The security team wanted the same check there, with three rules: every session gets Guardian without anyone installing it, each developer signs in as themselves through company single sign-on, and nobody shares a Semgrep token.
Guardian’s normal sign-in can’t finish inside a cloud container. This post shows how the team worked around that with a setup script, a two-link sign-in and one environment variable.
Why the normal sign-in stops in a cloud session
On a laptop, Guardian signs in with OAuth. Semgrep’s authentication guide describes it as a one-time browser sign-in when you first use the plugin; the credentials land in ~/.semgrep/guardian.yml and refresh themselves.
That sign-in finishes by sending the browser back to a 127.0.0.1 address: the machine running Guardian, where the plugin is listening. On a laptop that’s the same machine as the browser. In a cloud session it isn’t. Guardian runs in the container, the browser runs on the developer’s laptop, and 127.0.0.1 on the laptop has nothing listening, so the sign-in can never complete. Worse, the plugin starts this attempt as soon as the session starts and holds the login lock while it waits, which blocks any other way of signing in.
Semgrep’s documented fallback for developers who can’t complete a browser sign-in is a read-only token that every developer shares, available on Semgrep Enterprise. Semgrep itself recommends OAuth instead. Revoking a shared token affects everyone who depends on it, and shared credentials are rate-limited as a single user, which can throttle scans when many developers run Guardian at once. The team wanted each developer signed in as themselves, so it kept per-user sign-in.
The classic sign-in still works
Guardian also supports the older sign-in the Semgrep command-line tool has always used. The same guide says to ask the Guardian MCP server to sign in “using the legacy method”. Instead of waiting for a browser, it produces a link containing a one-time cli-token. Whoever opens that link while signed in to Semgrep approves it, and the session receives its own token.
That is something a cloud session can do, if three problems are solved:
- the plugin’s stuck OAuth attempt has to be ended so the classic sign-in can start;
- the link Guardian tries to open in a browser has to be caught and shown to the developer instead;
- the developer has to be told, clearly and repeatedly, that the session isn’t protected until they approve it.
A setup script that does the work
Claude Code on the web runs each session in a cloud environment that controls network access, environment variables and a setup script, which runs before Claude starts. On Team and Enterprise plans, an owner can share an environment with every member of the organisation. The team built one organisation environment with Guardian preinstalled.
The script pins the Semgrep command-line tool, installs the Guardian plugin from Anthropic’s official plugin marketplace, and sets the notice every developer sees:
NOTICE="It is the expectation of the security team that all code generated by Claude Code \
is run through the Semgrep Guardian plug-in. This has been installed for you in this \
session but it requires login to be activated to use the company licence and ruleset."SEMGREP_VERSION=1.183.0 # pinned; bump deliberately after testing
PLUGIN=semgrep@claude-plugins-official
MARKETPLACE=anthropics/claude-plugins-officialNext, it puts a stand-in for xdg-open, the command Guardian uses to open a browser, in ~/.local/bin. The stand-in fetches the page Guardian points at, pulls out the cli-token link and saves it to a file in /tmp. Nothing is opened, and the link never lands in the developer’s workspace:
cat > "$HOME/.local/bin/xdg-open" <<'EOF'
#!/bin/sh
# Headless stand-in for Semgrep Guardian login: save the sign-in link instead of
# opening a browser. Only legacy cli-token links are kept.
( sleep 1
url=$(curl -sS --noproxy '*' "$1" 2>/dev/null \
| grep -oE 'https://semgrep\.dev/login\?cli-token=[^"]+' | head -1)
[ -n "$url" ] || case "$1" in *cli-token=*) url="$1" ;; esac
[ -n "$url" ] && echo "$url" > /tmp/semgrep-login-url.txt
) >/dev/null 2>&1 &
exit 0
EOF
chmod +x "$HOME/.local/bin/xdg-open"A small Python helper does the rest. Run as a background process, it talks to Guardian’s MCP server directly and keeps asking for the classic sign-in. If Guardian answers that a sign-in is already in progress, the helper ends the plugin’s stuck OAuth attempt and tries again:
deadline = time.time() + DAEMON_MAX_WAIT
try:
while time.time() < deadline:
if logged_in():
return
err, text = tool("login", {"method": "legacy"})
if err and "already in progress" in text:
end_plugin_oauth()
time.sleep(2)
elif err:
time.sleep(10)def end_plugin_oauth():
"""End the plugin's automatic OAuth attempt, which holds the login lock."""
for p in glob.glob("/proc/[0-9]*/cmdline"):
try:
with open(p, "rb") as f:
args = f.read().split(b"\0")
except OSError:
continue
if b"auto" in args and b"SessionStart" in args and \
any(b"guardian" in a or b"scripts/hook" in a for a in args):
try:
os.kill(int(p.split("/")[2]), signal.SIGTERM)
except OSError:
passFinally, the script registers two Claude Code hooks: one when a session starts and one on every prompt the developer sends. Each shows the notice and the sign-in steps until the developer is signed in, then goes quiet. If the session link isn’t ready within the first 25 seconds, the first message gives the SSO step and the link follows with the next prompt:
hooks["SessionStart"].append({"matcher": "startup|resume", "hooks": [
{"type": "command", "timeout": 40, "command": f"python3 -I {helper} start"}]})
hooks["UserPromptSubmit"].append({"hooks": [
{"type": "command", "timeout": 10, "command": f"python3 -I {helper} prompt"}]})Each hook sends its message two ways: as a message in the session, and as context that tells Claude to repeat the notice and both links word for word before answering. Claude’s reply is where developers actually look, so the notice is far less likely to scroll past unseen:
def emit(event, url):
text = notice()
# Terminal banner: plain text (markdown is not rendered there).
msg = (text + "\n\n" if text else "") + body(url)
# Claude's reply renders markdown, so the notice is shown in bold there.
# …
print(json.dumps({"systemMessage": msg, "hookSpecificOutput": {
"hookEventName": event, "additionalContext": ctx}}))What the developer sees
The first prompt in a new session brings up the notice, in bold, with two numbered links.
Link 1 signs the developer in to Semgrep. Opened cold, Semgrep’s own login page asks for an email address to find the company’s identity provider.
The company link goes straight through single sign-on instead, and lands in Semgrep already signed in to the company’s organisation.
Link 2 authorises this session. Because the developer is already signed in, the cli-token link needs one click.
When the developer tells Claude they’re done, Claude checks Guardian’s status and confirms scanning is on. It even rewrote the file from before sign-in so that it went through the scan.
Why the company link skips the email prompt
The company link is a short address on the company’s own domain. Behind it, an existing redirect service answers with an HTTP 302 to the Microsoft My Apps launcher for the Semgrep enterprise application. The launcher signs the developer in to Entra ID using OpenID Connect with PKCE; in practice they’re usually signed in already, so this takes a moment. A Conditional Access session-control proxy checks the session on the way through.
Entra then starts the sign-in to Semgrep itself, sending a SAML assertion to Semgrep, which is how this company’s Semgrep single sign-on is set up. Because the identity provider starts the sign-in, Semgrep never needs to ask which company the user belongs to, so there’s no email page.
Semgrep’s own guidance points the same way. Its guide to the “Authentication method doesn’t match requested” error notes that it only happens when sign-in starts from Semgrep, and advises starting from your identity provider instead. Semgrep fixed IdP-initiated SAML sign-in in December 2025.
One environment variable
The environment also sets MCP_TOOL_TIMEOUT=600000, ten minutes for an MCP tool call. The team needed it while getting sign-in working, when a sign-in call made through Claude could sit waiting for the developer to click Activate. In the final script the helper talks to Guardian’s MCP server directly, so that wait no longer goes through Claude Code. Claude Code’s environment variable reference now gives a default far longer than ten minutes, so on current versions this setting shortens the limit rather than raising it. Check whether you need it before copying it.
Proof that it works
To show the check doing its job, the developer asked Claude for a deliberately vulnerable function: a database lookup built by putting the username straight into the SQL text. Guardian scanned the file in the background as soon as Claude wrote it and flagged two problems on the same line.
Asked to fix it, Claude switched to a parameterised query and tested both a normal lookup and the injection attempt, which now matched nothing. Guardian raised nothing on the rewrite. It reports findings with the agent’s next action and sends nothing for a clean file, so no warning is the signal you get, not an explicit pass.
Before you copy this
- Narrow network access. The environment shown uses Full access. Claude Code environments also offer Limited access with an allowlist; for this setup, the package registries, GitHub and Semgrep’s hosts are the likely needs.
- Keep secrets out of environment variables. Anyone who uses an environment can read its variables; Claude Code’s network secrets are the place for keys. This design never needs a shared token, which is the point.
- Pin what you install. The script pins the Semgrep version but not the package hash, and installs the latest Guardian plugin. Installing from a hash-locked requirements file (
pip install --require-hashes -r …), and deciding whether plugin updates should arrive automatically, closes both gaps. - Remember the timing. Guardian’s findings arrive with the agent’s next step, and a clean file produces no message.
The full setup script
The complete script, as used apart from company-specific names, paths and the SSO address. Paste it into a cloud environment’s setup script, or download it.
#!/bin/bash
# Semgrep Guardian headless login for Claude Code cloud sessions.
# Paste into: cloud environment menu > Edit > Setup script.
#
# Installs:
# semgrep CLI (pip, pinned) and the Semgrep Guardian Claude Code plugin
# ~/.local/bin/xdg-open saves Guardian's sign-in link instead of opening a
# browser (kept in /tmp, never in the workspace)
# /opt/company/semgrep-login.py start - SessionStart hook: begins the legacy login
# and shows the SSO step + link at session start
# prompt - UserPromptSubmit hook: repeats them on each
# prompt until the user is logged in
# daemon - background legacy login (ends the plugin's
# automatic OAuth attempt, which cannot finish
# in a cloud session and blocks other logins)
# Each user signs in as themselves; no shared SEMGREP_APP_TOKEN is used.
set -euo pipefail
# --- Notice shown (in bold) above the sign-in steps. Edit freely. ----------
NOTICE="It is the expectation of the security team that all code generated by Claude Code \
is run through the Semgrep Guardian plug-in. This has been installed for you in this \
session but it requires login to be activated to use the company licence and ruleset."
OPT=/opt/company
SEMGREP_VERSION=1.183.0 # pinned; bump deliberately after testing
PLUGIN=semgrep@claude-plugins-official
MARKETPLACE=anthropics/claude-plugins-official
mkdir -p "$OPT" "$HOME/.local/bin" "$HOME/.claude"
# --- Semgrep CLI ------------------------------------------------------------
if [ "$(semgrep --version 2>/dev/null)" != "$SEMGREP_VERSION" ]; then
python3 -m pip install --quiet --root-user-action=ignore "semgrep==$SEMGREP_VERSION" \
|| python3 -m pip install --quiet --root-user-action=ignore --break-system-packages \
"semgrep==$SEMGREP_VERSION"
fi
echo "Semgrep CLI: $(semgrep --version)"
# --- Semgrep Guardian plugin for Claude Code --------------------------------
# Org managed settings may also install it; a user-scope install alongside is
# harmless (same files) and makes sure it is there before the first session.
if command -v claude >/dev/null 2>&1; then
claude plugin marketplace add "$MARKETPLACE" >/dev/null 2>&1 || true # already added is fine
claude plugin install "$PLUGIN" --scope user
else
echo "WARNING: claude CLI not found; Semgrep plugin not installed" >&2
fi
# --- Headless browser stand-in ----------------------------------------------
cat > "$HOME/.local/bin/xdg-open" <<'EOF'
#!/bin/sh
# Headless stand-in for Semgrep Guardian login: save the sign-in link instead of
# opening a browser. Only legacy cli-token links are kept.
( sleep 1
url=$(curl -sS --noproxy '*' "$1" 2>/dev/null \
| grep -oE 'https://semgrep\.dev/login\?cli-token=[^"]+' | head -1)
[ -n "$url" ] || case "$1" in *cli-token=*) url="$1" ;; esac
[ -n "$url" ] && echo "$url" > /tmp/semgrep-login-url.txt
) >/dev/null 2>&1 &
exit 0
EOF
chmod +x "$HOME/.local/bin/xdg-open"
# --- Login helper -----------------------------------------------------------
printf '%s\n' "$NOTICE" > "$OPT/semgrep-notice.txt"
cat > "$OPT/semgrep-login.py" <<'PYEOF'
#!/usr/bin/env python3
"""Semgrep Guardian legacy login for headless Claude Code sessions.
semgrep-login.py start SessionStart hook
semgrep-login.py prompt UserPromptSubmit hook
semgrep-login.py daemon background login loop (started by `start`)
"""
import glob, json, os, signal, subprocess, sys, time
SSO_URL = "https://semgrep.example.com"
URL_FILE = "/tmp/semgrep-login-url.txt"
PID_FILE = "/tmp/semgrep-login-daemon.pid"
TOKEN_FILE = os.path.expanduser("~/.semgrep/settings.yml")
DAEMON_MAX_WAIT = 900 # seconds the background login keeps trying
START_WAIT = 25 # seconds the SessionStart hook waits for the link
NOTICE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"semgrep-notice.txt")
def notice():
"""The notice text set at the top of the setup script (empty if none)."""
try:
with open(NOTICE_FILE) as f:
return " ".join(f.read().split())
except OSError:
return ""
def logged_in_quick():
try:
with open(TOKEN_FILE) as f:
return any(l.startswith("api_token:") for l in f)
except OSError:
return False
def current_link():
try:
with open(URL_FILE) as f:
url = f.read().strip()
return url if "cli-token=" in url else None
except OSError:
return None
def body(url):
if url:
return ("Semgrep sign-in needed for this session:\n"
f" 1. SSO into the Semgrep app first: {SSO_URL}\n"
f" 2. Then open this link to authorize this session: {url}")
return (f"Semgrep sign-in needed: SSO into the Semgrep app first at {SSO_URL}. "
"The authorization link is being prepared and will be shown with "
"your next prompt.")
def emit(event, url):
text = notice()
# Terminal banner: plain text (markdown is not rendered there).
msg = (text + "\n\n" if text else "") + body(url)
# Claude's reply renders markdown, so the notice is shown in bold there.
shown = (f"**{text}**\n\n" if text else "") + body(url)
if url:
ctx = ("Semgrep Guardian is not logged in for this session. Before anything "
"else in your reply, show the user the following exactly, keeping the "
"bold notice and both links:\n" + shown + "\nAfter they approve it, "
"call the Semgrep Guardian status tool to confirm scanning is on.")
else:
ctx = ("Semgrep Guardian is not logged in yet. Before anything else in your "
"reply, show the user the following exactly, keeping the bold "
"notice:\n" + shown)
print(json.dumps({"systemMessage": msg, "hookSpecificOutput": {
"hookEventName": event, "additionalContext": ctx}}))
def daemon_running():
try:
with open(PID_FILE) as f:
os.kill(int(f.read().strip()), 0)
return True
except (OSError, ValueError):
return False
def start_daemon():
if daemon_running():
return
p = subprocess.Popen([sys.executable, "-I", os.path.abspath(__file__), "daemon"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
with open(PID_FILE, "w") as f:
f.write(str(p.pid))
def cmd_start():
sys.stdin.read() if not sys.stdin.isatty() else None
if logged_in_quick():
return
try:
os.remove(URL_FILE) # never show a link from an earlier session
except OSError:
pass
start_daemon()
deadline = time.time() + START_WAIT
while time.time() < deadline and not current_link() and not logged_in_quick():
time.sleep(1)
if not logged_in_quick():
emit("SessionStart", current_link())
def cmd_prompt():
sys.stdin.read() if not sys.stdin.isatty() else None
if logged_in_quick():
return
start_daemon() # restarts the login if an earlier attempt gave up
emit("UserPromptSubmit", current_link())
def end_plugin_oauth():
"""End the plugin's automatic OAuth attempt, which holds the login lock."""
for p in glob.glob("/proc/[0-9]*/cmdline"):
try:
with open(p, "rb") as f:
args = f.read().split(b"\0")
except OSError:
continue
if b"auto" in args and b"SessionStart" in args and \
any(b"guardian" in a or b"scripts/hook" in a for a in args):
try:
os.kill(int(p.split("/")[2]), signal.SIGTERM)
except OSError:
pass
def cmd_daemon():
roots = sorted(glob.glob(os.path.expanduser(
"~/.claude/plugins/cache/claude-plugins-official/semgrep/*/")))
if not roots:
return
root = roots[-1].rstrip("/")
srv = subprocess.Popen([f"{root}/scripts/hook", "claude", "mcp"],
env=dict(os.environ, CLAUDE_PLUGIN_ROOT=root),
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, bufsize=1)
ids = [0]
def call(method, params=None, notify=False):
msg = {"jsonrpc": "2.0", "method": method}
if params is not None:
msg["params"] = params
if not notify:
ids[0] += 1
msg["id"] = ids[0]
srv.stdin.write(json.dumps(msg) + "\n")
srv.stdin.flush()
if notify:
return None
for line in srv.stdout: # blocks until the reply (login: until approved)
try:
reply = json.loads(line)
except ValueError:
continue
if reply.get("id") == ids[0]:
return reply
raise SystemExit("guardian server exited")
def tool(name, args=None):
r = call("tools/call", {"name": name, "arguments": args or {}})
res = r.get("result", {})
text = "".join(c.get("text", "") for c in res.get("content", []))
return bool(res.get("isError") or "error" in r), text
def logged_in():
err, text = tool("status")
try:
return not err and json.loads(text).get("state") == "ok"
except ValueError:
return False
call("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "semgrep-login", "version": "2"}})
call("notifications/initialized", notify=True)
deadline = time.time() + DAEMON_MAX_WAIT
try:
while time.time() < deadline:
if logged_in():
return
err, text = tool("login", {"method": "legacy"})
if err and "already in progress" in text:
end_plugin_oauth()
time.sleep(2)
elif err:
time.sleep(10)
finally:
srv.terminate()
for f in (URL_FILE, PID_FILE):
try:
os.remove(f)
except OSError:
pass
if __name__ == "__main__":
{"start": cmd_start, "prompt": cmd_prompt, "daemon": cmd_daemon}[sys.argv[1]]()
PYEOF
chmod +x "$OPT/semgrep-login.py"
# --- Register the hooks (merged into existing settings) ---------------------
python3 -I - "$HOME/.claude/settings.json" "$OPT/semgrep-login.py" <<'PYEOF'
import json, os, sys
path, helper = sys.argv[1], sys.argv[2]
try:
with open(path) as f:
cfg = json.load(f)
except (OSError, ValueError):
cfg = {}
hooks = cfg.setdefault("hooks", {})
def keep(h):
cmd = h.get("command", "")
# drop earlier copies of these hooks, the previous login hooks, and the
# old check that told users to set a shared SEMGREP_APP_TOKEN
return not any(s in cmd for s in (helper, "/opt/company/semgrep-",
"semgrep show identity"))
for event in ("SessionStart", "UserPromptSubmit"):
groups = []
for g in hooks.get(event, []):
g["hooks"] = [h for h in g.get("hooks", []) if keep(h)]
if g["hooks"]:
groups.append(g)
hooks[event] = groups
hooks["SessionStart"].append({"matcher": "startup|resume", "hooks": [
{"type": "command", "timeout": 40, "command": f"python3 -I {helper} start"}]})
hooks["UserPromptSubmit"].append({"hooks": [
{"type": "command", "timeout": 10, "command": f"python3 -I {helper} prompt"}]})
cfg.setdefault("enabledPlugins", {})["semgrep@claude-plugins-official"] = True
cfg.setdefault("extraKnownMarketplaces", {}).setdefault("claude-plugins-official", {
"source": {"source": "github", "repo": "anthropics/claude-plugins-official"}})
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
json.dump(cfg, f, indent=2)
PYEOF
echo "Semgrep login setup installed."