MCP servers for Android development

MCP servers connect AI coding agents to Android build tools, device control, and project data through a standard JSON-RPC protocol configured in .mcp.json. About 25 minutes.

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.json format, 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.json the same way they review gradle.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.json is 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.

ConceptWhere it livesExample
Server config.mcp.json{ "command": "node", "args": [".mcp-servers/gradle.js"] }
Tool schemaserver codeJSON Schema: module (string, required), task (string)
Transport.mcp.json type keystdio, http (sse is deprecated)
Guard rail.claude/settings.json hookPreToolUse 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, and resources/read. Prompts and sampling are also part of the protocol specification.
  • Claude Code reads .mcp.json at the project root. The top-level key is mcpServers; a stdio entry has type, command, optional args, and optional env.
  • stdio transport 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 PreToolUse hook in .claude/settings.json can inspect the tool name and arguments before execution. Use it to block calls that touch keystore files, 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.json or in the server code. .mcp.json supports ${VAR} expansion, so reference an environment variable each developer sets locally.
  • A remote MCP server (http transport) 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 command and args, 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 stdio transport: the agent spawns them as child processes and communicates over stdin/stdout. No network port is opened.
  • env passes 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 answers tools/list with a JSON Schema for each tool, and handles tools/call by running the matching command and returning the output as the result.
  • GRADLE_OPTS sets 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

Agent ran a production Gradle task because the MCP tool schema was too loose
  • A team wired a Gradle-runner MCP server into Claude Code with a single task string parameter and no allow-list.
  • During a late-night session the agent called ./gradlew assembleRelease and 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 fix
  • The team added a PreToolUse hook in .claude/settings.json that blocks any tool call whose arguments contain publish, release, or deploy.
  • The Gradle-runner tool schema was tightened: task now accepts an enum of allowed tasks (testDebugUnitTest, lintDebug, assembleDebug) instead of a free-form string.
  • A PostToolUse hook was added to log every tool call to a file so the team could audit what the agent ran.
MCP server crashed silently and the agent fell back to guessing
  • 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 fix
  • The team moved the ADB path to an env variable in .mcp.json with a fallback to which 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 SessionStart hook was added that runs adb version and 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 publish or clean. 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 signingConfigs in build.gradle or overwrite a keystore. A PreToolUse hook that blocks edits to paths matching *.jks, *.keystore, or signingConfigs prevents 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: true in 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 the command and args first; 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)

  1. Create a file .mcp.json at the root of any Android project. Add a single mcpServers entry named gradle-runner with command set to node, args set to [".mcp-servers/gradle-server.js"], env with PROJECT_ROOT set to ".", and type set to "stdio". Do not add any secret values to env.

  2. Create the directory .mcp-servers/ and add a file gradle-server.js (or .py, .ts – any language you have). The file must implement two handlers: one that responds to tools/list by returning a JSON array with one tool named runTask whose input schema is { "type": "object", "properties": { "module": { "type": "string" }, "task": { "type": "string", "enum": ["testDebugUnitTest", "lintDebug", "assembleDebug"] } }, "required": ["module", "task"] }, and one that responds to tools/call by running ./gradlew :<module>:<task> and returning stdout as the result.

  3. 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 /mcp and confirm that gradle-runner is connected and offers runTask.

  4. Ask the agent to run runTask with module set to app and task set to lintDebug. Confirm that Gradle output appears in the session. Then ask it to run task set to publish. Confirm that the call is rejected because publish is not in the enum (make your server check the enum too; do not rely on the agent alone).

  5. Add a PreToolUse hook in .claude/settings.json that reads the tool input from stdin and exits with code 2 when it contains the string keystore or signingConfig. Test it by asking the agent to edit the build.gradle signing 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.

Next: Gemini Agent Mode and Android skills