MCP servers for Android development
Why it matters
- Claude Code can already read files and run shell commands like
./gradlew test. MCP adds structured access to systems outside the repo (an issue tracker, a design tool, docs, a device or crash dashboard), so you stop pasting data into the chat by hand. - Interviewers at AI-forward teams ask how you wire an agent into a real Android CI pipeline. Knowing the
.mcp.jsonformat, transport options, and tool schemas is the difference between 'I used a chatbot' and 'I built an agent workflow'. - A misconfigured MCP server (wrong transport, missing env var, unscoped tool) can let an agent run arbitrary shell commands in your repo. Senior engineers review
.mcp.jsonthe same way they reviewgradle.properties. - MCP is an open protocol, so one server can serve several agents: Claude Code reads
.mcp.json, and the agent in Android Studio can also connect to MCP servers. Understanding the protocol lets you reuse custom servers across tools.
The simple explanation
- Your Android project is a workshop. The AI agent is a new hire who can read blueprints (source files) but cannot operate the machines (Gradle, ADB, Firebase console).
- MCP is the set of labelled buttons on a control panel: 'Run tests', 'Start emulator', 'Read logcat'.
.mcp.jsonis the wiring diagram that tells the agent which button controls which machine.- JSON-RPC is the language the agent and the machine speak: a request with a method name and arguments, a response with a result or an error.
- A tool schema (JSON Schema) is the instruction label on each button: what inputs it accepts and what it returns.
- Without MCP the hire can only suggest changes; with MCP the hire can actually run the build and read the output.
MCP (Model Context Protocol) is a JSON-RPC 2.0 protocol that lets an AI agent discover and call external tools. In an Android project the agent (Claude Code, the Android Studio agent, or a custom agent) connects to an MCP server (for a local server it starts it as a child process), sends a tools/list request to discover available tools, then calls tools/call with a tool name and a JSON argument object.
Configuration. Claude Code reads project servers from .mcp.json at the repo root, or you add them with claude mcp add (scopes: local, project, user). Each entry under mcpServers names a server and its type: stdio servers have a command, optional args and env; http servers have a url and optional headers. The sse type is deprecated in favour of http. Claude Code asks you to approve project servers from .mcp.json before using them.
Tool schema. Every tool exposes a JSON Schema for its inputs and a description string. The agent uses the description to decide when to call the tool; the schema validates arguments before the call reaches your server. A Gradle-runner tool might accept { "module": "feature-auth", "task": "testDebugUnitTest" }.
Lifecycle. A stdio server process lives for the session. When the session starts, the agent connects and lists tools; on each tools/call the server does the work and returns a result or an error. In Claude Code, MCP tools are named mcp__<server>__<tool>, so a PreToolUse hook (covered in the CLAUDE.md lesson) can match them and block a dangerous call before it runs. Run /mcp to see server status.
| Concept | Where it lives | Example |
|---|---|---|
| Server config | .mcp.json | { "command": "node", "args": [".mcp-servers/gradle.js"] } |
| Tool schema | server code | JSON Schema: module (string, required), task (string) |
| Transport | .mcp.json type key | stdio, http (sse is deprecated) |
| Guard rail | .claude/settings.json hook | PreToolUse with matcher mcp__gradle-runner__.* blocks risky calls |
Check the current MCP docs for the latest transport options and supported agent runtimes.
Notes
- MCP is JSON-RPC 2.0 over a transport. The core methods include
tools/list,tools/call, andresources/read. Prompts and sampling are also part of the protocol specification. - Claude Code reads
.mcp.jsonat the project root. The top-level key ismcpServers; a stdio entry hastype,command, optionalargs, and optionalenv. stdiotransport means the agent spawns the server as a child process and talks over stdin/stdout. No network port is opened, which makes it a good default for local Android work.- Each tool must declare a JSON Schema for its inputs. If the schema is missing or too loose, the agent may pass malformed arguments and the server crashes or runs the wrong Gradle task.
- A
PreToolUsehook in.claude/settings.jsoncan inspect the tool name and arguments before execution. Use it to block calls that touchkeystorefiles,signingConfigs, or any path containing a secret. - Skills and MCP are different layers: a skill is instructions (a folder with
SKILL.md, the open Agent Skills standard), an MCP server is a callable tool. A skill can tell the agent when to call an MCP tool. - Never put an API key, a keystore password, or a Firebase service-account JSON as a literal in
.mcp.jsonor in the server code..mcp.jsonsupports${VAR}expansion, so reference an environment variable each developer sets locally. - A remote MCP server (
httptransport) sends tool calls over the network. Treat it like a third-party dependency: use HTTPS, trust only known providers, and scope the tools it exposes. - Review every MCP server the same way you review a CI script: read the
commandandargs, check what shell access it has, and confirm it cannot read or write files outside the project root.
Code example
This .mcp.json wires three local MCP servers into a Claude Code session for an Android project: a Gradle task runner, an ADB device controller, and a logcat reader. Each entry shows the minimum fields an agent needs to start and talk to the server.
{
"mcpServers": {
"gradle-runner": {
"command": "node",
"args": [".mcp-servers/gradle-server.js"],
"env": {
"PROJECT_ROOT": ".",
"GRADLE_OPTS": "-Dorg.gradle.jvmargs=-Xmx2g"
},
"type": "stdio"
},
"adb-device": {
"command": "python3",
"args": [".mcp-servers/adb_server.py"],
"env": {
"ADB_PATH": "/usr/local/bin/adb",
"DEVICE_SERIAL": "emulator-5554"
},
"type": "stdio"
},
"logcat-reader": {
"command": "node",
"args": [".mcp-servers/logcat-server.js"],
"type": "stdio"
}
}
}- All three servers use
stdiotransport: the agent spawns them as child processes and communicates over stdin/stdout. No network port is opened. envpasses only non-secret configuration (project root, ADB path, device serial). A keystore password or Firebase token must never appear here as a literal.- Each server file (
.mcp-servers/gradle-server.js, etc.) is your own code. It answerstools/listwith a JSON Schema for each tool, and handlestools/callby running the matching command and returning the output as the result. GRADLE_OPTSsets the JVM heap for the Gradle runs the server starts, so large multi-module builds do not run out of memory.- The server names and scripts here are examples you write yourself, not packages you can install.
Run the idea in plain Kotlin
data class ToolCall(val name: String, val args: Map<String, String>)
data class ToolResult(val success: Boolean, val output: String)
class McpServer {
private val tools: MutableMap<String, (Map<String, String>) -> String> = mutableMapOf()
fun registerTool(name: String, handler: (Map<String, String>) -> String) {
tools[name] = handler
}
fun handleRequest(call: ToolCall): ToolResult {
val handler: ((Map<String, String>) -> String)? = tools[call.name]
if (handler == null) {
return ToolResult(false, "Unknown tool: " + call.name)
}
return try {
val output: String = handler(call.args)
ToolResult(true, output)
} catch (e: Exception) {
ToolResult(false, "Error: " + (e.message ?: "unknown"))
}
}
fun listTools(): List<String> {
return tools.keys.toList()
}
}
fun main() {
val server = McpServer()
server.registerTool("runTests") { args: Map<String, String> ->
val module: String = args["module"] ?: "app"
"Running ./gradlew :" + module + ":testDebugUnitTest"
}
server.registerTool("lintProject") { args: Map<String, String> ->
val module: String = args["module"] ?: "core"
"Running ./gradlew :" + module + ":lintDebug"
}
server.registerTool("listDevices") { args: Map<String, String> ->
"adb devices: emulator-5554 device"
}
val requests: List<ToolCall> = listOf(
ToolCall("runTests", mapOf("module" to "feature-auth")),
ToolCall("lintProject", mapOf("module" to "core")),
ToolCall("listDevices", emptyMap<String, String>()),
ToolCall("deployToPlay", mapOf("version" to "2.1.0"))
)
println("MCP Server - Tool Call Simulation")
println("==================================")
println()
for (req in requests) {
val result = server.handleRequest(req)
val status: String = if (result.success) "OK" else "FAIL"
println("[" + status + "] " + req.name + " -> " + result.output)
}
println()
val toolNames: List<String> = server.listTools()
println("Registered tools: " + toolNames.joinToString(", "))
}In production
- A team wired a Gradle-runner MCP server into Claude Code with a single
taskstring parameter and no allow-list. - During a late-night session the agent called
./gradlew assembleReleaseand then./gradlew publish, pushing a half-built AAR to the internal Maven repo. - The CI dashboard showed an unexpected publish event; no human had triggered it.
- The team added a
PreToolUsehook in.claude/settings.jsonthat blocks any tool call whose arguments containpublish,release, ordeploy. - The Gradle-runner tool schema was tightened:
tasknow accepts an enum of allowed tasks (testDebugUnitTest,lintDebug,assembleDebug) instead of a free-form string. - A
PostToolUsehook was added to log every tool call to a file so the team could audit what the agent ran.
- A logcat-reader MCP server used a hard-coded ADB path that did not exist on a new developer's machine.
- The server process exited immediately. It showed as failed in
/mcp, but nobody checked, and the agent worked without any logcat tools. - The agent then guessed error messages from memory, producing incorrect fixes that took two days to trace back to the missing logcat data.
- The team moved the ADB path to an
envvariable in.mcp.jsonwith a fallback towhich adb. - The server now starts even when ADB is missing and returns a clear tool error explaining the problem, so the agent can tell the user instead of guessing.
- A
SessionStarthook was added that runsadb versionand fails fast with a clear message if the binary is missing.
Common mistakes
- Putting a keystore password or API key in .mcp.json env. The file is committed to version control and read by the agent in plain text. The correct approach is
${VAR}expansion from a local environment variable, or a secrets-manager lookup that the server does at runtime, never the secret value itself. - Using a free-form string schema for a Gradle task parameter. The agent can pass any string, including
publishorclean. Define an enum of allowed task names in the tool's JSON Schema so the server rejects anything outside the list before it reaches the shell. - Adding a remote MCP server you do not trust. A compromised or careless remote server can return malicious tool results (prompt injection) that the agent acts on. Use HTTPS, trust only known providers, and scope the server to the minimum set of tools the project needs.
- Skipping the PreToolUse hook for file-editing tools. Without a guard, the agent can edit
signingConfigsinbuild.gradleor overwrite a keystore. APreToolUsehook that blocks edits to paths matching*.jks,*.keystore, orsigningConfigsprevents this class of incident. - Letting the server crash instead of returning an error. If the server dies, its tools disappear and the agent may carry on guessing. Catch failures and return a tool result marked as an error (
isError: truein MCP) with a clear message the agent can act on. - Approving project servers without reading them. Claude Code asks before it uses servers from a cloned repo's
.mcp.json. Read thecommandandargsfirst; a malicious entry runs code on your machine.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is MCP and how does it differ from just letting the agent run shell commands?”
“How do you configure an MCP server for Claude Code in an Android project?”
“What goes wrong when an MCP server crashes mid-session, and how do you handle it?”
“How do MCP servers interact with CLAUDE.md, skills, and hooks in a Claude Code session?”
Quiz
What protocol does MCP use for communication between the agent and the server?
Where does Claude Code read MCP server configuration from?
Which hook event should you use to block an MCP tool call that edits a keystore file?
What is the safest transport for a local MCP server in an Android project?
0 of 4 answered
Mini task
Wire a Gradle-runner MCP server into a Claude Code session (15 min)
-
Create a file
.mcp.jsonat the root of any Android project. Add a singlemcpServersentry namedgradle-runnerwithcommandset tonode,argsset to[".mcp-servers/gradle-server.js"],envwithPROJECT_ROOTset to".", andtypeset to"stdio". Do not add any secret values toenv. -
Create the directory
.mcp-servers/and add a filegradle-server.js(or.py,.ts– any language you have). The file must implement two handlers: one that responds totools/listby returning a JSON array with one tool namedrunTaskwhose input schema is{ "type": "object", "properties": { "module": { "type": "string" }, "task": { "type": "string", "enum": ["testDebugUnitTest", "lintDebug", "assembleDebug"] } }, "required": ["module", "task"] }, and one that responds totools/callby running./gradlew :<module>:<task>and returning stdout as the result. -
Open Claude Code (terminal, VS Code, or Android Studio). Start a new session in the project root and approve the project server when asked. Run
/mcpand confirm thatgradle-runneris connected and offersrunTask. -
Ask the agent to run
runTaskwithmoduleset toappandtaskset tolintDebug. Confirm that Gradle output appears in the session. Then ask it to runtaskset topublish. Confirm that the call is rejected becausepublishis not in the enum (make your server check the enum too; do not rely on the agent alone). -
Add a
PreToolUsehook in.claude/settings.jsonthat reads the tool input from stdin and exits with code 2 when it contains the stringkeystoreorsigningConfig. Test it by asking the agent to edit thebuild.gradlesigning block; the hook should block the edit.
Done when: the agent can run lintDebug through the MCP tool, cannot run publish (enum rejection), and cannot edit signing config (hook rejection). All three checks pass without you running any command manually.